Jest how to assert that function is not called

In Jest there are functions like tobeCalled or toBeCalledWith to check if a particular function is called. Is there any way to check that a function is not called?

85739 次浏览

Just use not.

expect(mockFn).not.toHaveBeenCalled()

看看 开玩笑的文件

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

But using toHaveBeenCalledTimes with zero does the trick:

期望(嘲笑)

请按照玩笑中的文档: Https://jestjs.io/docs/en/mock-functions#mock-property

所有模拟函数都有这个特殊的。属性,该属性保存有关如何调用函数以及函数返回内容的数据。那个。Mock 属性还跟踪每个调用的 this 值,因此也可以检查这个: [ ... ]

These mock members are very useful in tests to assert how these functions get called, instantiated, or what they returned:

// 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);

最新版本的 Jest (22.x 及以上版本)收集了相当不错的模拟函数调用统计数据,只需查看 他们的文件即可。

calls属性显示调用的次数、传递给 mock 的参数、返回的结果等等。你可以直接访问它,作为 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');

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

然而,你也可以使用 Jest 的 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
});

在极少数情况下,您甚至可以考虑编写自己的 fixture 来进行计数。比如说,如果你很注重条件反射或者在状态下工作,这可能会很有用。

希望这个能帮上忙!