I have a function in my application which returns a true or false by checking a second function. And this function will disable/enable the input field.
Now I want to spy on the first function and call this with a specific value.
I know that this is possible in Jasmine with spyOn and .and.returnValue. And with that I can cover the different cases for when the function returns a true or false.
How can I call a function in Jest with a specific value?
My code:
<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
}
}
So I want to cover the function when testData2 is defined as null, this means that testFunctionB will return testFunctionA.
I want to make sure that the function testFunctionA is true and that testFunctionB also returns true. So I can cover the multiple cases.
This is what I tried:
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)
})
So I try to put a spy on testFunctionA and return a true or false.
How can I do this?
CodePudding user response:
In order to cover your test case, you need to mock testFunctionA before you call setProps({testData2: null}). That's because wrapper.setProps(...) is what triggers the evaluation of 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);
})
