test-utils icon indicating copy to clipboard operation
test-utils copied to clipboard

Mock adding third random parameter

Open joelsantosbr opened this issue 1 year ago • 3 comments

Environment

  • Operating System: Linux
  • Node Version: v20.10.0
  • Nuxt Version: 3.9.3
  • CLI Version: 3.10.0
  • Nitro Version: 2.8.1
  • Package Manager: [email protected]
  • Builder: -
  • User Config: devtools, modules, devServer, srcDir, css, postcss, i18n, runtimeConfig
  • Runtime Modules: @nuxt/test-utils/[email protected], @nuxtjs/[email protected]
  • Build Modules: -

Reproduction

https://stackblitz.com/edit/spy-use-fetch-is-not-working?file=src%2FuseLogin.nuxt.test.ts

Describe the bug

I'm trying to create a spy for nuxt's composable useFetch and validate what is being passed as a parameter in the call, but for some reason a third random parameter is added image

Additional context

No response

Logs

No response

joelsantosbr avatar Jan 30 '24 16:01 joelsantosbr

I can confirm I have the same problem when spying the useFetch method. However, the third parameter on my side is $dk08ZMi4Ri …!

antoinezanardi avatar Jan 30 '24 20:01 antoinezanardi

@antoinezanardi I discovered here https://github.com/nuxt/test-utils/issues/567#issuecomment-1836958045 that we need to use registerEndpoint to mock the useFetch response, it worked for me, but it is limited, you can't change the responses based on each test, you would need to create a test file to validate an error response and another for success, this suggestion was said here by someone else https://github.com/nuxt/test-utils/issues/551#issuecomment-1836958018

joelsantosbr avatar Jan 31 '24 13:01 joelsantosbr

@antoinezanardi I discovered here #567 (comment) that we need to use registerEndpoint to mock the useFetch response, it worked for me, but it is limited, you can't change the responses based on each test, you would need to create a test file to validate an error response and another for success, this suggestion was said here by someone else #551 (comment)

Sweet technique, I missed that! I actually was also able to change the response, even within a test, in the following way:

// usual imports...
const { responseMock } = vi.hoisted(() => {
  return {
    responseMock: vi.fn().mockImplementation(() => {
      console.log("called base!");
      return { testDataOfResponse: "baseline" };
    }),
  };
});
registerEndpoint("/test/", () => responseMock())

The previous code is added at the top of the test file, while then, in the test:

// it("test name", () => {
      responseMock.mockImplementation(() => {
          console.log("called modified!");
          return { testDataOfResponse: "test-related response" };
      });
// });

You can call the .mockImplementation method as many times as you want within a test :)

ennioVisco avatar Mar 02 '24 07:03 ennioVisco