no-such-module.ts
declare module 'no-such-module' {
export function sum(a: number, b: number): number;
}
sum.ts
import { sum } from 'no-such-module';
export const func = (a: number, b: number) => sum(a, b);
sample.test.ts
jest.mock('no-such-module');
const { sum } = require('no-such-module');
sum.mockImplementation((a,b) => a+b);
describe('sample test', () => {
it('should pass', () => {
expect(sum(1, 2)).toBe(3);
});
});
Error
Cannot find module 'no-such-module' from 'sample.test.ts'
> 1 | jest.mock('no-such-module');
| ^
2 | const { sum } = require('no-such-module');
3 |
4 | sum.mockImplementation((a,b) => a+b);
Is it possible to mock a node module that doesn't exist yet? I declared a no-such-module
in a ts file. I am trying to mock a function from the module.
Mocking Node modules If the module you are mocking is a Node module (e.g.: lodash ), the mock should be placed in the __mocks__ directory adjacent to node_modules (unless you configured roots to point to a folder other than the project root) and will be automatically mocked. There's no need to explicitly call jest.
Mock functions allow you to test the links between code by erasing the actual implementation of a function, capturing calls to the function (and the parameters passed in those calls), capturing instances of constructor functions when instantiated with new , and allowing test-time configuration of return values.
mock replaces one module with either just jest. fn , when you call it with only the path parameter, or with the returning value of the function you can give it as the second parameter.
The mock module has the identical interface as its source module, but all its methods are dummies, and imports , declarations , providers and exports have been mocked respectively. To turn a module into a mock module, simply pass its class into MockModule function. TestBed.
jest.mock('no-such-module', () => {
return {
sum: (a,b) => a+b
};
}, { virtual: true });
const { sum } = require('no-such-module');
we need to pass options { virtual: true }
to jest.mock()
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