我有使用 puppetteer
的函数的page
对象来评估和返回一些数据。
我想用 jest
写一个单元测试检查是否 page.evaluate()
接受指定的参数
这是功能
async function cinemasfromState(page, state) {
const CINEMA_SELECTOR = `div[data-state=$[STATE]] div.top-select-option a.eccheckbox`;
let res = await page.evaluate(
(elementPath, state) => {
let results = Array.from(document.querySelectorAll(elementPath)).map(
function(cin, index) {
return {
//Stuff
};
return result;
},
{ state }
);
},
CINEMA_SELECTOR.replace("$[STATE]", state),
state
);
return res;
}
下面是我的测试的样子
describe("cinemasfromState", () => {
let page_mock = {
click: jest.fn(() => Promise.resolve()),
evaluate: jest.fn((selector, state) => Promise.resolve())
};
test("page.evaluate called correctly ", async () => {
await cinemasfromState(page_mock, "KAN");
expect(page_mock.evaluate).toBeCalledTimes(1);
expect(
page_mock.evaluate)toBeCalledWith(
"div[data-state=KAN] div.top-select-option a.eccheckbox",
"KAN"
);
});
});
我得到以下错误作为我的测试输出
● cinemasfromState › page.evaluate called correctly
expect(jest.fn()).toBeCalledWith(expected)
Expected mock function to have been called with:
"div[data-state=KAN] div.top-select-option a.eccheckbox"
as argument 1, but it was called with
[Function anonymous].
Difference:
Comparing two different types of values. Expected string but received function.
"KAN"
as argument 2, but it was called with
"div[data-state=KAN] div.top-select-option a.eccheckbox".
undefined
as argument 3, but it was called with
"KAN".
Difference:
Comparing two different types of values. Expected undefined but received string.
52 | expect(page_mock1.evaluate).toBeCalledTimes(1);
53 | expect(page_mock1.evaluate).toBeCalledWith(
> 54 | "div[data-state=KAN] div.top-select-option a.eccheckbox",
| ^
55 | "KAN"
56 | );
57 | });
对编写测试以验证论点有任何帮助吗?
最佳答案
如果你阅读你的错误日志,你会注意到它试图匹配三个参数,但你只断言两个。 .toBeCalledWith
in jest 将对传递给函数的参数及其顺序进行精确匹配。
例如,如果您调用 func(arg1, arg2)
,然后 expect(func).toBeCalledWith(arg2)
将失败,因为您还没有断言 arg1
.这就是您的情况发生的情况,因为 page.evaluate()
的第一个参数实际上是一个匿名函数。
所以,你的测试需要是这样的:
expect(page_mock.evaluate).toBeCalledWith(
expect.any(Function),
"div[data-state=KAN] div.top-select-option a.eccheckbox",
"KAN"
);
关于javascript - 在 Jest 中使用 toBeCalledWith() 测试参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53246007/