I'm trying to figure out manual mocks in Jest. I think this should be easy...but it isn't.
My project directories are like
Both models/user.js and models/__mocks__/user.js have the same code:
module.exports = {
    create(username, password) {
        return new Promise(function(resolve, reject) {
            setTimeout(function() {
                resolve({"username":username, "password": password});
            }, 100);
        });
    }
}
The file __tests__/user-test.js 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 fine, 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");
});
It doesn't work, and spits out:
 FAIL  __tests__\user-test.js
  ● user 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)
                To spy on an exported function in jest, you need to import all named exports and provide that object to the jest. spyOn function. That would look like this: import * as moduleApi from '@module/api'; // Somewhere in your test case or test suite jest.
The jest. fn method is, by itself, a higher-order function. It's a factory method that creates new, unused mock functions. Also, as we discussed previously, functions in JavaScript are first-class citizens.
Ah! Figured it out! My folder structure is fine. Turns out I had a misunderstanding as to what "jest.mock" actually did. "jest.mock" changes the behavior of the node "require" function to use the mock, it doesn't do a require itself.
My test should have looked like:
jest.mock('../models/user');
test('user creation works', () => {
    const user = require('../models/user');
    return user.create("mitchell", "boo");
});
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With