I’m kinda stuck with testing composition-functions. I’m using vitest with @vue/test-utils, but also found no good way to get it to work with jest.
My issue is: How do I test composable functions, which use other composable functions? And how do I correctly mock the functions return values?
Let’s say I have a composition like this:
import {useExternalComposition} from '@/composables/externalComposition'
export function useFoo() {
function isConditionTrue(condition) {
if (condition) {
return false;
}
return true;
}
async function bar() {
const { externalFunction1, externalFunction2} = useExternalComposition();
const isTrue = isConditionTrue(true);
try {
if (isTrue) {
await externalFunction1();
return;
}
await externalFunction2();
} catch(e) {
console.error(e);
}
}
return {
bar,
isConditionTrue
}
}
With vitest I was not able to figure out a way, to correctly test bar, in detail to mock results from isConditionTrue and externalFunction1 and externalFunction2.
This was my best approach for now:
it('should call isConditionTrue', async function () {
const useFooVar = useFoo();
const spy = vi
.spyOn(useFooVar, 'isConditionTrue')
.mockImplementationOnce(() => true);
expect(spy.getMockName()).toEqual('isConditionTrue'); // true
await useFooVar.bar();
expect(spy).toHaveBeenCalled(); // AssertionError: expected "isConditionTrue" to be called at least once
});
What do I miss?
I tried multiple ways of mocking/spying functions, and expected to have a correct assertion