Kiran Mali
Kiran Mali

Reputation: 657

vitest failed to mock quasar

I am having vue3 app with vite and vitest and trying to mock the Quasar useQuasar composable which I am using in my custom Composable like:

// useLoginRequestBuilder.ts
import { makeUserAuthentication } from "@/main/factories"
import { useQuasar } from "quasar"

export function useLoginRequestBuilder() {
  const $q = useQuasar()

  async function login() {
    try {
      $q.loading.show()
      const auth = makeUserAuthentication()
      return await auth.signinRedirect()
    } catch (e) {
      console.log(e)
      $q.loading.hide()
      $q.notify({
        color: "red-4",
        textColor: "white",
        icon: "o_warning",
        message: "Login Failed!",
      })
    }
  }

  return {
    login,
  }
}

and I am trying to mock quasar in tests like:

// useLoginRequestBuilder.spec.ts

import { useLoginRequestBuilder } from "@/main/builders"

vi.mock("quasar", () => ({ // <--- this is not really mocking quasar
  useQuasar: () => ({
    loading: {
      show: () => true,
      hide: () => true,
    },
  }),
}))

const spyAuth = vi.fn(() => Promise.resolve(true))

vi.mock("@/main/factories", () => ({
  makeUserAuthentication: () => ({
    signinRedirect: () => spyAuth(),
  }),
}))

describe("test useLoginRequestBuilder", () => {
  test("should call signinRedirect", async () => {
    const { login } = useLoginRequestBuilder()
    const sut = await login()
    expect(sut).toBe(true)
  })
})

vi.mock("quasar"... is failing to mock quasar and I am getting below error. That means, it failed to mock and failed to get the $q.loading.... object.

TypeError: Cannot read properties of undefined (reading 'loading')

I understand that there is a separate testing lib for quasar, here but I think this is not really the case here.

Upvotes: 3

Views: 920

Answers (1)

Beerswiller
Beerswiller

Reputation: 679

Bordering on a necro-post, but I had a similar issue that the mocking factory wasn't creating the plugins being used in non-Vue components, and had to mock each call individually in the end.

Though I'd add it here for anyone else

vitest.mock("quasar", () => vi.fn()); // this doesn't mock out calls

// use individual mocks as below
import { Loading } from "quasar";
vi.spyOn(Loading, "show").mockImplementation(() => vi.fn());
vi.spyOn(Loading, "hide").mockImplementation(() => vi.fn());

Upvotes: 1

Related Questions