【问题标题】:How to call a function in Jest with a specific value?如何在 Jest 中调用具有特定值的函数?
【发布时间】:2023-03-18 22:57:01
【问题描述】:

我的应用程序中有一个函数,它通过检查第二个函数来返回真或假。此功能将禁用/启用输入字段。

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

我知道 spyOn.and.returnValue 在 Jasmine 中是可能的。这样我就可以涵盖函数返回 true 或 false 的不同情况。

如何在 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将返回testFunctionA

我想确保函数testFunctionA 为真并且testFunctionB 也返回真。所以我可以涵盖多种情况。

这是我尝试过的:

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 上放置一个间谍并返回真或假。 我该怎么做?

【问题讨论】:

    标签: javascript vue.js unit-testing jestjs


    【解决方案1】:

    为了覆盖您的测试用例,您需要在调用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);
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-01-08
      • 1970-01-01
      • 2017-06-01
      • 2020-11-25
      • 1970-01-01
      • 2015-04-20
      • 1970-01-01
      相关资源
      最近更新 更多