In my Vue 3 app, I use the pattern of having a composable that contains methods that will handle fetching some data from various APIs. The reason they’re composables rather than simple functions is that there’s some route metadata that I need to grab from useRoute
/useRouter
, plus data from some other composables in the app.
The composable looks like this
const useHelpMateApi = () => {
// A bunch of setup code preceding the functions...
async function fetchHelpMate(id: string) {
return await fetch(// Fetching occurs here);
}
return { fetchHelpMate }
}
I then have a Vue component that will call this API onBeforeMount
, like this
// In a <script setup> tag
const { params } = useRoute();
const { fetchHelpMate } = useHelpMateApi();
onBeforeMount(async () => fetchHelpMate(params.id).then((response) => (// do stuff with response));
I’m trying to write a vitest test that checks whether the fetchHelpMate
method gets called here with the correct argument (the route’s ID), but I can’t figure out how to write the test.
I’ve tried a dozen different formats for this test, the latest one at which point I decided to ask this question being the one below
t('should fetch the HelpMate with the correct ID', () => {
const spyFetchHelpMate = vi.fn(useHelpMateApi().fetchHelpMate);
component = mount(BotSettings, { global: { plugins: [router, pinia] } });
expect(spyFetchHelpMate).toHaveBeenCalledOnce();
});