如何使用特定值调用 Jest 中的函数?

How to call a function in Jest with a specific value?

我的应用程序中有一个函数,它 return 通过检查第二个函数判断真或假。而此函数将 disable/enable 输入字段。

现在我想监视第一个函数并用特定值调用它。

我知道在 spyOn.and.returnValue 的 Jasmine 中这是可能的。这样我就可以涵盖函数 return 为真或假时的不同情况。

如何使用特定值调用 Jest 中的函数?

我的代码:

<input
 :id="id"
 v-model="searchKey"
 :disabled="testFunctionB"
 type="text"
 name="search box"
 autocomplete="off"
>   

computed: {
    testFunctionA () {
      if(!this.testData) return false 
      return this.testData1 !== ''
    },
    testFunctionB () {
      if (this.testData2 === false) return false
      return this.testFunctionA
    }
}

所以我想覆盖testData2定义为null时的函数,也就是说testFunctionB会returntestFunctionA.

我想确保函数 testFunctionA 为真,并且 testFunctionB 也 return 为真。所以我可以涵盖多个案例。

这是我试过的:

it('should disable the input when the testData2 value is not defined and the testFunctionA is true', async () => {
        await wrapper.setProps({testData2: null})
        wrapper.vm.testFunctionA = jest.fn()
        wrapper.vm.testFunctionA.mockReturnValueOnce(true)

        expect(wrapper.vm.testFunctionB).toBe(true)
})

所以我试着在 testFunctionA 和 return 上进行间谍活动。 我该怎么做?

为了覆盖您的测试用例,您需要在调用 setProps({testData2: null}) 之前模拟 testFunctionA。那是因为 wrapper.setProps(...) 触发了 testFunctionB:

的计算
it('should disable the input when the testData2 value is not defined and the testFunctionA is true', async () => {
 jest.spyOn(wrapper.vm, 'testFunctionA').mockReturnValueOnce(true);
 await wrapper.setProps({testData2: null});
 expect(wrapper.vm.testFunctionB).toBe(true);
})