Import function from a Jest manual mock with Typescript

前端 未结 2 1229
[愿得一人]
[愿得一人] 2021-01-03 02:09

I\'m creating a custom mock (of an ES6 class) with Jest in a Typescript project. The mock creates end exports a few mock.fn() so that they could be spied on in

2条回答
  •  星月不相逢
    2021-01-03 03:00

    I have the same problem and I only have a workaround. My problem is that I manually mock fs from node.

    So I have a manual mock for 'fs' which looks roughly like this:

    const fs = jest.genMockFromModule("fs");
    
    let mockFiles = {};
    
    function __clearMocks(){
        mockFiles = {};
    }
    
    module.exports = fs;
    

    So clearly when my test case imports fs it would not work:

    import * as fs from 'fs';
    fs.__clearMocks();
    

    To get this working I create an extension of the type:

    declare module 'fs' {
        export function __clearMocks(): void; 
    }
    

    So now I can modify my testcase like this:

    import * as fs from 'fs';
    import 'fsExtension';
    fs.__clearMocks();
    

    Hopefully this helps you!

提交回复
热议问题