Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mock a node module that doesn't exist yet?

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.

like image 323
lch Avatar asked Jul 25 '19 22:07

lch


People also ask

How do you mock a node 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.

What does Jest mock () do?

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.

What is the difference between Jest FN and Jest mock?

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.

What is a mock module?

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.


1 Answers

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()

like image 64
lch Avatar answered Oct 15 '22 08:10

lch