我正在尝试在内部使用回调测试功能。我设置了一个模拟功能,但是我还需要测试一个回调。
我试图将其作为另一个模拟功能进行分离,但它并不算作覆盖。
我要测试的功能:
export const checkDescription = async page => {
const metaDescription = await page.$eval(
'meta[name="description"]',
description => description.getAttribute("content")
);
return metaDescription;
};
我嘲笑了页面功能:
const page = {
$eval: jest.fn(() => "Value")
};
我的测试:
test("Should return description", async () => {
expect(await checkDescription(page)).toBe("Value");
expect(page.$eval).toHaveBeenCalled();
});
我试图分开描述:
const description = {
getAttribute: jest.fn(() => "Value")
};
但是我认为这不是在$ eval中覆盖描述的正确方法。
答案 0 :(得分:0)
您已经关闭!
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
});