![](/img/trans.png)
[英]How to mock module in different ways in different tests in the same test file in Jest?
[英]How to clear a module mock between tests in same test suite in Jest?
我模擬了一些 nodejs 模塊(例如,其中一個是fs
)。 我將它們放在__mocks__
文件夾中(與node_modules
相同級別)文件夾中,模塊 mocking 有效。 但是,無論我使用哪個“測試清除之間”選項,下一個測試都不是“沙盒”。 這里出了什么問題?
模擬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()
結果:
1
, 2
1
, undefined
1
, 2
1
, undefined
有人知道我做錯了什么嗎? 如何清除同一套件中測試之間的模塊模擬? 如有必要,我很樂意澄清。 謝謝!
重置模塊並為每個測試再次要求它們:
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();
});
}
我在上面的解決方案中遇到了問題。 我設法用下一個片段解決了這個問題。
afterEach(() => {
Object.keys(mockedModule).forEach(method => mockedModule[method].mockReset())
})
不過,我更願意使用本機方法來執行此操作。 類似mockedModule.mockReset()
東西。
對於局部變量,聲明的 scope 很重要。
const mockFunc1 = jest.fn() // possibly bad mock reset/clear between tests
describe('useGetMetaData', () => {
const mockFunc2 = jest.fn() // good mock reset/clear between tests
afterEach(() => {/* reset/clear mocks */})
test.todo('implement tests here')
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.