轉載位址 React16 Jest單元測試 之 Mock Functions(Mock Return Values)
項目初始化【這裡使用之前的項目,節省時間】
項目初始化位址
https://github.com/durban89/webpack4-react16-reactrouter-demo.git
tag:v_1.0.20
拉取
git clone https://github.com/durban89/webpack4-react16-reactrouter-demo.git
cd webpack4-react16-reactrouter-demo
git fetch origin
git checkout v_1.0.20
npm install
Mock Return Values
Jest的模拟函數(Mock function)也可以用來在測試中注入測試值到測試的代碼中,如下
const myMock = jest.fn();
console.log(myMock);
myMock
.mockReturnValueOnce(10)
.mockReturnValueOnce('x')
.mockReturnValue(true);
console.log(myMock(), myMock(), myMock(), myMock(), myMock());
運作npx jest src/__tests__/jest_mock_return_values.test.js --notify --watchman=false 後輸出的結果類似如下
console.log src/__tests__/jest_mock_return_values.test.js:2
{ [Function: mockConstructor]
_isMockFunction: true,
getMockImplementation: [Function],
mock: [Getter/Setter],
mockClear: [Function],
mockReset: [Function],
mockRestore: [Function],
mockReturnValueOnce: [Function],
mockResolvedValueOnce: [Function],
mockRejectedValueOnce: [Function],
mockReturnValue: [Function],
mockResolvedValue: [Function],
mockRejectedValue: [Function],
mockImplementationOnce: [Function],
mockImplementation: [Function],
mockReturnThis: [Function],
mockName: [Function],
getMockName: [Function] }
console.log src/__tests__/jest_mock_return_values.test.js:9
10 'x' true true true
模拟函數(Mock function)在使用函數continuation-passing風格的代碼中也非常有效。以這種風格編寫的代碼有助于避免需要複雜的存根,以重新建立它們所代表的真實元件的行為,進而傾向于在使用它們之前直接将值注入測試中。具體看如下代碼
const filterTestFn = jest.fn();
// 第一次mock傳回true,第二次mock傳回false
filterTestFn.mockReturnValueOnce(true).mockReturnValueOnce(false);
const result = [11, 12].filter(filterTestFn);
console.log(result);
console.log(filterTestFn.mock.calls);
運作npx jest src/__tests__/jest_mock_return_values.test.js --notify --watchman=false 後得到的結果類似如下
console.log src/__tests__/jest_mock_return_values.test.js:20
[ 11 ]
console.log src/__tests__/jest_mock_return_values.test.js:22
[ [ 11, 0, [ 11, 12 ] ], [ 12, 1, [ 11, 12 ] ] ]
現實世界中大多數的例子實際上是在依賴的元件上擷取模拟函數并對其進行配置,但技術是相同的。在這些情況下,盡量避免在沒有直接測試的任何函數内部實作邏輯。
項目實踐位址
https://github.com/durban89/webpack4-react16-reactrouter-demo.git
tag:v_1.0.21