我正在使用 jest 和 enzyme 来测试我的应用。我有一个功能:
const someFunc = (arg1, arg2, arg3) => {
arg2.someOtherFunc(arg3);
}
现在,我想为函数 someFunc
编写测试,我已经模拟了 someOtherFunc
并且我将测试它是否会被一些 arg3 调用但是我'我不知道我应该如何编写断言?
我的测试应该断言在 someFunc
之后,它应该调用带有一些参数的 someOtherFunc
。
最佳答案
在您的情况下,您希望将函数作为回调传递 在您的测试中,您必须模拟它并检查它是否被调用/被调用 n 次或使用特定参数调用。
检查下面这个例子:
// your function
const someFunc = (arg1, arg2, arg3) => {
arg2.someOtherFunc(arg3);
}
// your test file
it("works", () => {
const arg1 = 'im just any value doesnt matter';
const arg2 = {
someOtherFunc: jest.fn(),
};
const arg3 = 'argument';
someFunc(arg1, arg2, arg3);
// some assertions you can use
expect(arg2.someOtherFunc).toBeCalled();
expect(arg2.someOtherFunc).toBeCalledWith('argument');
expect(arg2.someOtherFunc).toHaveBeenCalledTimes(1);
});
关于javascript - 如何使用 Jest 和 enzyme 为调用另一个函数的函数编写测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51174265/