如何用玩笑测试对同一函数的特定调用序列 [英] How to test a specific sequence of calls to the same function with jest
问题描述
我正在尝试测试一个类,该类在玩笑中对模拟函数进行了一系列调用:
I have a class I'm trying to test that makes a sequence of calls to a mock function in jest:
我有一个Gpio
类构造函数的模拟,该模拟在这些属性后面创建对象实例.模拟类具有用于digitalWrite
的模拟方法:
I have a mock for the Gpio
class constructor that creates the object instances behind these properties. The mock class has a mock method for digitalWrite
:
运行测试时,我可以看到对digitalWrite的调用顺序:
And when I run my test I can see the sequence of calls made to digitalWrite:
但是我不知道如何测试顺序是否正确.我觉得如果我可以看到测试失败提示中的序列,我应该能够说先呼叫0,然后呼叫0,然后呼叫1",但我不太清楚该怎么做它.有什么想法吗?
But I can't figure out how to test that the sequence is correct. I feel like if I can see the sequence in the test fail hint I should be able to say "call first with a 0, then with a 0, then with a 1", but I can't quite figure out how to do it. Any ideas?
也不要这样指出:我知道从技术上讲每个引脚实例都应该是独立的,并且我应该能够分别测试它们,但是以开玩笑的方式嘲笑构造方法,我必须使用digitalWrite
具有相同的模拟功能.
Also so that it doesn't get pointed out: I know that technically each of the pin instances should be separate and I should be able to test them individually, but with the way you mock constructors in jest I have to use the same mock function for digitalWrite
.
推荐答案
You can use jest's .toHaveBeenNthCalledWith()
例如
it('should be called in the following sequence', () => {
expect(......digitalWrite).toHaveBeenNthCalledWith(1, 0)
expect(......digitalWrite).toHaveBeenNthCalledWith(2, 0)
expect(......digitalWrite).toHaveBeenNthCalledWith(3, 1)
})
或者您可以使用模拟功能的 mock.calls 属性:
or you can use the mock function's mock.calls property:
it('should be called in the following sequence', () => {
expect(......digitalWrite).toHaveProperty('mock.calls', [
[0], [0], [1]
])
})
这篇关于如何用玩笑测试对同一函数的特定调用序列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!