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

标签 javascript node.js unit-testing jestjs

我模拟了一些 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())

当我在 afterEach() 中运行时,在第一次和第二次运行 init() 后,我分别得到以下 existsSync() 结果:

  • jest.resetModules() :12
  • existsSync.mockReset(): 1, 未定义
  • existsSync.mockClear(): 1, 2
  • existsSync.mockRestore(): 1, 未定义

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

最佳答案

重置模块并在每次测试时再次需要它们:

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

关于javascript - 如何在 Jest 中的同一测试套件中的测试之间清除模块模拟?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52561147/

相关文章:

javascript - 如何使用 Word 的 Javascript API 清除 Word 撤消堆栈

mysql - 如何使用nodejs在mysql中使用like查询

node.js - 在 Node 项目上运行 make 命令

asp.net-mvc - MVC .NET如何在现有源代码中添加单元测试项目?

unit-testing - 如何在编写单元测试用例时将 Cucumber 特征文件中的整数数组传递给步骤定义

javascript - 如何消除移动设备的 'Render-blocking JavaScript' 错误

当文档准备好时,Javascript 调用 $(document).on ('click'

javascript - dc.js 渲染阿根廷 map

javascript - 无法在 Node.js 应用程序中解析从 Azure 服务总线接收到的 JSON 消息

c# - 如何断言事件已被 FakeItEasy 订阅?