开玩笑如何断言该功能



在Jest中,有诸如tobeCalledtoBeCalledWith之类的功能来检查是否调用了特定函数。有什么方法可以检查函数未调用?

只需使用not

expect(mockFn).not.toHaveBeenCalled()

请参阅开玩笑的文档

not对我不起作用,扔 Invalid Chai property: toHaveBeenCalled

但是将toHaveBeenCalledTimes与零一起使用可以:

expect(mock).toHaveBeenCalledTimes(0)

JEST(22.x和Onwards)的最新版本收集了相当不错的模拟功能统计数据,只需查看其文档。

calls属性向您显示了呼叫的数量,传递给模拟的参数,结果返回了。您可以直接访问它,作为mock的属性(例如,以@christian Bonzelet在他的答案中建议的方式):

// The function was called exactly once
expect(someMockFunction.mock.calls.length).toBe(1);
// The first arg of the first call to the function was 'first arg'
expect(someMockFunction.mock.calls[0][0]).toBe('first arg');
// The second arg of the first call to the function was 'second arg'
expect(someMockFunction.mock.calls[0][1]).toBe('second arg');

我个人更喜欢这种方式,因为它为您提供了更大的灵活性,并保持代码清洁器,以防您测试产生不同数量的调用的不同输入。

但是,自最近以来,您也可以将速记别名用于开玩笑的expect(间谍匹配者别名PR)。我猜.toHaveBeenCalledTimes在这里很适合:

test('drinkEach drinks each drink', () => {
  const drink = jest.fn();
  drinkEach(drink, ['lemon', 'octopus']);
  expect(drink).toHaveBeenCalledTimes(2); // or check for 0 if needed
});

在极少数情况下,您甚至可能想考虑编写自己的固定装置。例如,如果您在调理或与状态下工作,这可能很有用。

希望这会有所帮助!

请遵循嘲笑的文档:https://jestjs.io/docs/en/mock-functions#mock-property

所有模拟函数都具有此特殊的.mock属性,这是有关如何调用函数以及保留返回函数的数据的地方。.Mock属性还跟踪每个呼叫的值,因此也可以检查一下:[...]

这些模拟成员在测试中非常有用,可以断言这些功能是如何被调用,实例化或返回的内容的:

// The function was called exactly once
expect(someMockFunction.mock.calls.length).toBe(1);

或...

// The function was not called
expect(someMockFunction.mock.calls.length).toBe(0);

最新更新