jest.mock() method returns undefined when passing a valid module name

Viewed 920

I have a dependency that i'm trying to mock with jest.mock() method but it returns undefined.

I already checked and its a valid import, because my test runs with the dependency instead of the mock, but somehow it keeps returning undefined

my .spec.ts file looks like this:

import validator from 'validator';

jest.mock('validator', () => ({
  isEmail(): boolean {
    return true;
  },
}));

describe('EmailValidator Adapter', () => {
  test('Should return false if validator returns false', () => {
    const sut = new EmailValidatorAdapter();
    jest.spyOn(validator, 'isEmail').mockReturnValueOnce(false);
    const isValid = sut.isValid('invalid_email@mail.com');
    expect(isValid).toBe(false);
  });
});

my jest.config.js file looks like this:

module.exports = {
  roots: ['<rootDir>/src', '<rootDir>/node_modules'],
  collectCoverageFrom: [
    '<rootDir>/src/**/*.ts',
    '!<rootDir>/src/**/*-protocols.ts',
    '!**/protocols/**',
  ],
  moduleDirectories: ['node_modules', '<rootDir>'],
  coverageProvider: 'babel',
  coverageDirectory: 'coverage',
  testEnvironment: 'node',
  transform: {
    '.+\\.ts': 'ts-jest',
  },
};

As you can see, I already put my node_modules folder in the roots array in the jest config file

1 Answers

I have found a workaround here: https://github.com/kulshekhar/ts-jest/issues/120

It seems to be related with the way Typescript deals with default exports

So, I changed my code to:

jest.mock('validator', () => {
  return {
    default: {
      isEmail: jest.fn().mockImplementation(() => true),
    },
  };
});

Related