Hand made object layout in jest

I am trying to figure out manual mockery in Jest. I think it should be easy ... but it is not.

My project catalogs are like

  • __ tests__
    • custom test.js
  • models
    • user.js
    • __ mocks__
      • user.js
  • node_modules
    • ...
  • package.json

Both /user.js and / __ mocks __ / user.js models have the same code:

module.exports = {
    create(username, password) {
        return new Promise(function(resolve, reject) {
            setTimeout(function() {
                resolve({"username":username, "password": password});
            }, 100);
        });
    }
}

The __tests __ / user-test.js file looks like this:

test('user creation works', () => {
    const user = require('../models/user');
    //const user = jest.mock('../models/user');
    return user.create("mitchell", "boo");
});

This works great, tests pass, but when I change it to:

test('user creation works', () => {
    //const user = require('../models/user');
    const user = jest.mock('../models/user');
    return user.create("mitchell", "boo");
});

This does not work and spits out:

 FAIL  __tests__\user-test.jsuser creation works

    TypeError: user.create is not a function

      at Object.<anonymous>.test (__tests__\user-test.js:4:17)
      at process._tickCallback (internal\process\next_tick.js:103:7)
+4
source share
1 answer

! ! . , , "jest.mock". "jest.mock" node "require", , .

:

jest.mock('../models/user');
test('user creation works', () => {
    const user = require('../models/user');
    return user.create("mitchell", "boo");
});
+10

Source: https://habr.com/ru/post/1666187/


All Articles