用笑话测试回调函数
Test callback function with jest
我正在尝试测试内部带有回调的函数。我设置了一个模拟函数,但我还需要测试一个回调。
我试图将它作为另一个模拟函数分开,但它不算作涵盖。
我要测试的功能:
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 中覆盖描述的正确方法。
你很接近!
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
});
我正在尝试测试内部带有回调的函数。我设置了一个模拟函数,但我还需要测试一个回调。
我试图将它作为另一个模拟函数分开,但它不算作涵盖。
我要测试的功能:
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 中覆盖描述的正确方法。
你很接近!
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
});