Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

API data mocking #567

Closed
tomsdob opened this issue Jun 1, 2023 · 3 comments
Closed

API data mocking #567

tomsdob opened this issue Jun 1, 2023 · 3 comments

Comments

@tomsdob
Copy link

tomsdob commented Jun 1, 2023

Hello, I'm having a hard time understanding and finding information on how to mock useFetch/useAsyncData returned data.
I've tried using the following as well as an MSW server included in vitest.setup.ts but with no success:

Here's an example component pages/test.vue:

<script setup>
const { data: users } = useFetch('https://jsonplaceholder.typicode.com/users');
</script>

<template>
  <ul>
    <li v-for="user in users" :key="user.id">
      <p>{{ user.id }}</p>
      <p>{{ user.name }}</p>
    </li>
  </ul>
</template>

pages/__tests__/Test.spec.ts:

// @vitest-environment nuxt
import { describe, expect, it } from 'vitest';
import { mount } from '@vue/test-utils';
import { mockNuxtImport } from 'nuxt-vitest/utils';
import Test from '../test.vue';

mockNuxtImport('useFetch', () => {
  return () =>
    vi.fn(() => {
      return {
        error: undefined,
        data: [
          {
            id: 1,
            name: 'John Doe',
          },
        ],
        pending: false,
        refresh: vi.fn(),
      };
    });
});

vi.stubGlobal('useFetch', () => {
  return () =>
    vi.fn(() => {
      return {
        error: undefined,
        data: [
          {
            id: 1,
            name: 'John Doe',
          },
        ],
        pending: false,
        refresh: vi.fn(),
      };
    });
});

describe('Test', () => {
  const wrapper = mount(Test);

  it('should render correctly', () => {
    expect(wrapper.html()).toMatchSnapshot();
  });
});

In the snapshot I can see that no data was fetched and nothing changes no matter which above mentioned method I try to mock the data with.
pages/__tests__/__snapshots__/Test.spec.ts.snap

// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html

exports[`Test > should render correctly 1`] = `"<ul></ul>"`;

vitest.config.ts

import { defineVitestConfig } from 'nuxt-vitest/config';

export default defineVitestConfig({
  test: {
    environment: 'happy-dom',
    setupFiles: ['./vitest.setup.ts'],
  },
});

vitest.setup.ts

import { rest } from 'msw';
import { setupServer } from 'msw/node';

const users = [
  {
    id: 1,
    name: 'John Doe',
  },
];

export const restHandlers = [
  rest.get('https://jsonplaceholder.typicode.com/users', (req, res, ctx) => {
    return res(ctx.status(200), ctx.json(users));
  }),
];

const server = setupServer(...restHandlers);

// Start server before all tests
beforeAll(() => server.listen({ onUnhandledRequest: 'error' }));

//  Close server after all tests
afterAll(() => server.close());

// Reset handlers after each test `important for test isolation`
afterEach(() => server.resetHandlers());
@ExEr7um
Copy link
Contributor

ExEr7um commented Jun 1, 2023

You can use registerEndpoint for that.

In my component I use baseURL.

<script>
const { data } = await useFetch("/test/", {
  baseURL: useRuntimeConfig().public.apiBase,
})
</script>

Then in nuxt.config.ts I make baseURL empty, so all request will go to nitro server.

export default defineNuxtConfig({
  $test: {
    runtimeConfig: {
      public: {
        apiBase: "",
      },
    },
  },
})

Then in test I use registerEndpoint.

registerEndpoint("/test/", () => "test data")

@ExEr7um
Copy link
Contributor

ExEr7um commented Jun 1, 2023

Added some info about it in danielroe/nuxt-vitest#198.

@tomsdob
Copy link
Author

tomsdob commented Jun 2, 2023

Thanks for the explanation, @ExEr7um!

@danielroe danielroe transferred this issue from danielroe/nuxt-vitest Dec 2, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants