![](/img/trans.png)
[英]Jest - mock a function being called from the function under test
[英]Jest: How to mock function and test that it was called?
我有一個遍歷數組並為每個元素發出HTTP請求的方法:
文件處理器.js
const chunkFile = (array) => {
return array.map(el => {
sendChunkToNode(el);
});
};
const sendChunkToNode = (data) =>
new Promise((resolve, reject) => {
request.post(...);
});
export default {
chunkFile,
sendChunkToNode,
};
我已經有一個sendChunkToNode測試:
describe("sendChunkToNode", () => {
beforeEach(() => {
// TODO: figure out how to mock request with certain params
nock(API.HOST)
.post(API.V1_UPLOAD_CHUNKS_PATH)
.reply(201, {
ok: true
});
});
it("makes a POST request to /api/v1/upload-chunks", async () => {
const response = await FileProcessor.sendChunkToNode(
1,
"not_encrypted",
"handle"
);
expect(response).toEqual({ ok: true });
});
});
我現在要測試chunkFile。 在測試中,我只想測試sendChunkToNode
是用不同的元素調用的。 像這樣:
describe("chunkFile", () => {
it("calls sendChunkToNode with each element", async () => {
expect(sendChunkToNode).toBeCalledWith(1) //<--- I made the toBeCalledWith method up
expect(sendChunkToNode).toBeCalledWith(2) //<--- I made the toBeCalledWith method up
chunkFile([1,2]);
});
});
Jest有辦法做到這一點嗎?
按照編寫方式,您應該進行循環並執行nock次數與數組中元素的數量一樣多。 然后,您調用chunkFile()
; 如果有未決的Nock請求,則表示出了點問題,測試將失敗。
test('...', () => {
const someArray = ['a', 'b', 'c']; // someArray.length == 3
someArray.forEach(element => {
nock(...); // set up nock using element value
});
// if the nock interceptors you set up don't match any request, it will throw an error
chunkFile(someArray);
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.