Closed belomx closed 7 months ago
I'd also be glad, if that feature could be introduced in test-utils. From my point of view lack of request mocking is critical issue.
you can mock any http requests in your test using msw
, please have a try
Although there is "server" in
setupServer
, the library does not establish any actual servers, but operates by augmenting native request issuing modules (such ashttps
orXMLHttpRequest
). The namespace is chosen for what the logic represents, not how it works internally.
package here: https://www.npmjs.com/package/msw vitest document: https://vitest.dev/guide/mocking.html#requests
got that using vi.stubGlobal
vi.stubGlobal("$fetch", () => MOCKED_RESPONSE);
There is a utility called registerEndpoint
for mocking requests: https://nuxt.com/docs/getting-started/testing#registerendpoint.
Would it be possible to entirely stub $fetch
with vi.fn()
?
registerEndpoint
is great to mock API responses on tests. But i'm looking for a way to check if I'm calling $fetch with the correct arguments, for example with .haveBeenCalledWith(...)
. Is that possible with @nuxt/test-utils?
Would it be possible to entirely stub
$fetch
withvi.fn()
?
registerEndpoint
is great to mock API responses on tests. But i'm looking for a way to check if I'm calling $fetch with the correct arguments, for example with.haveBeenCalledWith(...)
. Is that possible with @nuxt/test-utils?
I needed to stub the response from a pinia action, I used this which worked. Not sure if its the right approach.
import { useTestStore } from "~/stores/test";
import { setActivePinia, createPinia } from "pinia";
import { describe, it, expect, beforeEach, vi } from "vitest";
describe("Test Store", () => {
beforeEach(() => {
setActivePinia(createPinia());
});
it("sends message", async () => {
global.$fetch = vi.fn().mockResolvedValueOnce("Hello Nitro");
const testStore = useTestStore();
await testStore.testAction();
expect(testStore.getMessage).toBe("Hello Nitro");
});
});
Would it be possible to entirely stub
$fetch
withvi.fn()
?
registerEndpoint
is great to mock API responses on tests. But i'm looking for a way to check if I'm calling $fetch with the correct arguments, for example with.haveBeenCalledWith(...)
. Is that possible with @nuxt/test-utils?
it('calls the API with correct parameters on save', async () => {
const wrapper = await mountSuspended(Component, { props })
const vm = wrapper.vm
const mockFetch = vi.spyOn(global, '$fetch')
await vm.onSave()
expect(mockFetch).toHaveBeenCalledWith('/api/...', {
method: 'post',
body: {
adult: 2,
child: 1,
infant: 1,
},
})
})
Describe the feature
I couldn't find a way to mock the '$fetch' for rest calls to my api server.
I would like to mock the '$fetch' calls, for a specific url, e.g. GET 'server:34000/orders'. Even better, if this behavior could be set for the test or test group.
Additional information
Final checks