Ele*_*ena 12 javascript unit-testing callback jestjs puppeteer
我正在尝试测试一个带有回调的函数。我设置了一个模拟函数,但我还需要测试一个回调。
我试图将它作为另一个模拟函数分开,但它不算作覆盖。
我正在尝试测试的功能:
export const checkDescription = async page => {
const metaDescription = await page.$eval(
'meta[name="description"]',
description => description.getAttribute("content")
);
return metaDescription;
};
Run Code Online (Sandbox Code Playgroud)
我嘲笑了页面功能:
const page = {
$eval: jest.fn(() => "Value")
};
Run Code Online (Sandbox Code Playgroud)
我的测试:
test("Should return description", async () => {
expect(await checkDescription(page)).toBe("Value");
expect(page.$eval).toHaveBeenCalled();
});
Run Code Online (Sandbox Code Playgroud)
我试图分开描述:
const description = {
getAttribute: jest.fn(() => "Value")
};
Run Code Online (Sandbox Code Playgroud)
但我不认为这是在 $eval 中覆盖描述的正确方法。
你很接近!
该description
箭头功能传递到您的page.$eval
模拟功能,所以你可以使用mockFn.mock.calls
进行检索。
检索到它后,您可以直接调用它来测试它并获得完整的代码覆盖率:
test("Should return description", async () => {
expect(await checkDescription(page)).toBe("Value"); // Success!
expect(page.$eval).toHaveBeenCalled(); // Success!
const description = page.$eval.mock.calls[0][1]; // <= get the description arrow function
const getAttributeMock = jest.fn(() => 'mock content');
expect(description({ getAttribute: getAttributeMock })).toBe('mock content'); // Success!
expect(getAttributeMock).toHaveBeenCalledWith('content'); // Success!
// Success! checkDescription now has full code coverage
});
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
10203 次 |
最近记录: |