如何模拟尚不存在的节点模块?

时间:2019-07-25 22:52:21

标签: typescript jestjs ts-jest

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);
    });
});

错误

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

是否可以模拟尚不存在的节点模块?我在ts文件中声明了no-such-module。我正在尝试从模块中模拟功能。

1 个答案:

答案 0 :(得分:0)

jest.mock('no-such-module', () => {
    return {
        sum: (a,b) => a+b
    };
}, { virtual: true });

const { sum } = require('no-such-module');

我们需要将选项{ virtual: true }传递给jest.mock()