我正在學習用笑話和特別是模擬模塊進行單元測驗。我用一些數學方法在 math.js 檔案中撰寫了一些簡單的模塊:
const add = (a, b) => a b;
const subtract = (a, b) => b - a;
const multiply = (a, b) => a * b;
const divide = (a, b) => b / a;
module.exports = {
add,
subtract,
multiply,
divide
}
然后我將它包含在我的主 js 中,并像這樣進行模塊模擬:
jest.mock('./math.js');
const math = require('./math');
test("calls math.add", () => {
math.add(1, 2);
console.log(math.add.mock);
expect(math.add).toHaveBeenCalled();
expect(math.add).toHaveBeenCalledWith(1, 2);
expect(math.add).toHaveReturned();
expect(math.add).toHaveReturnedWith(3);
});
現在,當我運行測驗時,除了最后一個測驗之外,所有測驗都通過了:
expect(math.add).toHaveReturnedWith(3);
在控制臺中我看到:
● 呼叫 math.add
expect(jest.fn()).toHaveReturnedWith(expected)
Expected: 3
Received: undefined
Number of returns: 1
10 | expect(math.add).toHaveBeenCalledWith(1, 2);
11 | expect(math.add).toHaveReturned();
> 12 | expect(math.add).toHaveReturnedWith(3);
| ^
13 | });
和 console.log(math.add.mock) 給了我這個:
console.log
{
calls: [ [ 1, 2 ] ],
instances: [
{
add: [Function],
subtract: [Function],
multiply: [Function],
divide: [Function]
}
],
invocationCallOrder: [ 1 ],
results: [ { type: 'return', value: undefined } ],
lastCall: [ 1, 2 ]
}
所以看起來 math.add 模擬函式沒有回傳任何值。我的問題是為什么?我做錯了什么?
uj5u.com熱心網友回復:
使用后jest.mock('someModule'),jest 會為這個模塊創建一個自動模擬的版本。這意味著從這個模塊匯出的東西都是模擬的。
你可以認為 mockedmath.add方法是jest.fn(). 它沒有模擬實作。如果沒有給出實作,模擬函式將undefined在呼叫時回傳。這就是math.add(1, 2)回報的原因undefined。
您正在測驗math模塊,那么您不應該模擬它。但如果你堅持這樣做。您可以math.add.mockReturnValue(3);在呼叫之前使用math.add(1,2). 但這沒有意義,你可以給任何你想要的價值。你沒有測驗真正的math.add方法。您只需將模擬回傳值與斷言匹配expect(math.add).toHaveReturnedWith(3)
例如
math.js:
const add = (a, b) => a b;
const subtract = (a, b) => b - a;
const multiply = (a, b) => a * b;
const divide = (a, b) => b / a;
module.exports = {
add,
subtract,
multiply,
divide,
};
math.test.js:
const math = require('./math');
jest.mock('./math.js');
test('calls math.add', () => {
math.add.mockReturnValue(3);
math.add(1, 2);
expect(jest.isMockFunction(math.add)).toBeTruthy();
expect(math.add).toHaveBeenCalled();
expect(math.add).toHaveBeenCalledWith(1, 2);
expect(math.add).toHaveReturned();
expect(math.add).toHaveReturnedWith(3);
});
測驗結果:
PASS stackoverflow/71605818/math.test.js
? calls math.add (3 ms)
----------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
----------|---------|----------|---------|---------|-------------------
All files | 100 | 100 | 20 | 100 |
math.js | 100 | 100 | 20 | 100 |
----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 1.225 s
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/450115.html
標籤:javascript 单元测试 开玩笑的 嘲弄
