Search code examples
jestjsrequire

How correctly require in Jest file ? (with a module pattern js file)


Probably a stupid question

I start using JEST for testing.

I have my js app :

var app={ init:function{ //some code}, ... }
module.exports = app;

And my app.test.js :

const {app} = require('../js/index.js')

test('type of variable', () => {
  expect(typeof app.someFunction(app.someVar)).toBe("'number");
});

And I have the classic error :

TypeError: Cannot read property 'someFunction' of undefined

It seem very stupid, but I never understand clearly these require on client side... It work perfectly with the Jest getStarted example enter image description here

My arbo is

-js
----index.js
-tests
----app.text.js

Solution

  • module.exports = app
    

    The above line returns object {}, and you are trying to pick app from object in your destructing line var {app}

    Remove {}

    const app = require('../js/index.js')
    
    test('type of variable', () => {
      expect(typeof app.someFunction(app.someVar)).toBe("'number");
    });