代码之家  ›  专栏  ›  技术社区  ›  axm__

如何在Jest中清除同一测试套件中测试之间的模块模拟?

  •  0
  • axm__  · 技术社区  · 7 年前

    我模拟了一些nodejs模块(例如,其中一个是 fs ). 我把它们放在一个盒子里 __mocks__ 文件夹(同级) node_modules

    fs公司 模块是:

    // __mocks__/fs.js
    module.exports = {
        existsSync: jest.fn()
            .mockReturnValueOnce(1)
            .mockReturnValueOnce(2)
            .mockReturnValueOnce(3) 
    }
    

    init() 称为(见下文), existsSync 从值1开始:的第一个值 jest.fn().mockReturnValue()

    // init.test.js
    const init = require("../init");
    const { existsSync } = require("fs");
    jest.mock("fs");
    
    describe("initializes script", () => {
        afterEach(() => {
            // see below!
        });    
    
        test("it checks for a package.json in current directory", () => {
            init();
        });
    
        test("it stops script if there's a package.json in dir", () => {
            init(); // should be run in clean environment!
        });
    }
    

    再一次非常简化了init.js文件

    const { existsSync } = require("fs");
    console.log("value of mocked response : ", existsSync())
    

    existsSync() 第一次和第二次运行后 当我跑进去的时候 afterEach() :

    • jest.resetModules(): 1 , 2
    • 1 , undefined
    • 1 , 2
    • existsSync.mockRestore(): 1 未定义

    有人知道我做错了什么吗?如何清除同一套件中测试之间的模块模拟?如有必要,我很乐意澄清。谢谢!

    1 回复  |  直到 7 年前
        1
  •  6
  •   Alexandre Borela    7 年前

    describe("initializes script", () => {
        afterEach(() => {
            jest.resetModules() 
        });    
    
        beforeEach(() => {
            jest.mock("fs");
        })
    
        test("it checks for a package.json in current directory", () => {
            const init = require("../init");
            init();
        });
    
        test("it stops script if there's a package.json in dir", () => {
            const init = require("../init");
            init();
        });
    }
    
    推荐文章