我正在使用 fs 模塊將 html 字串匯入到我的模塊中,如下所示:
const fs = require('fs');
const htmlString = fs.readFileSync("../utils/htmlString.html").toString();
然后,在我的測驗檔案中,我試影像這樣模擬 fs 模塊:
const fs = require('fs');
jest.mock("fs", () => {
return {
readFileSync: jest.fn()
}
})
fs.readFileSync.mockReturnValue("test string");
我可能錯誤的邏輯告訴我它應該正確地模擬原始字串匯入并將其替換為“測驗字串”字串。但是,在運行測驗時它會拋出:
TypeError:無法讀取未定義的屬性“toString”
我知道這意味著模擬不成功,因為它應該在字串實體上成功呼叫 .toString() 。
我在這里做錯了什么?
uj5u.com熱心網友回復:
您不需要為jest.mock('fs'). jest.mock()在需要時使用自動模擬版本模擬模塊。這意味著fs.readFileSync是一個與 相同的模擬方法jest.fn()。
您需要確保在模擬回傳值后需要被測模塊,因為模塊范圍內的代碼將在需要時立即執行。
例如
index.js:
const fs = require('fs');
const htmlString = fs.readFileSync('../utils/htmlString.html').toString();
console.log('htmlString: ', htmlString);
index.test.js:
const fs = require('fs');
jest.mock('fs');
describe('70760704', () => {
test('should pass', () => {
expect(jest.isMockFunction(fs.readFileSync)).toBeTruthy();
fs.readFileSync.mockReturnValue('test string');
require('./');
});
});
測驗結果:
PASS stackoverflow/70760704/index.test.js (7.242 s)
70760704
? should pass (14 ms)
console.log
htmlString: test string
at Object.<anonymous> (stackoverflow/70760704/index.js:3:9)
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 7.279 s, estimated 8 s
jest.config.js:
module.exports = {
testEnvironment: 'node',
};
包版本:
"jest": "^26.6.3"
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/416270.html
標籤:
上一篇:控制器的單元測驗無法按預期作業
