Search code examples
vue.jsjestjsquasar-frameworkvue-test-utilsquasar

Jest Mocking with Quasar and Typescript


I want to mock Amplify Auth service in my test. There is no error, but test doesn't work because of my mock.

Here is the code I'm about to test:

  signIn(): void {
    if (!this.valid) return;
    this.loading = 1;
    this.$Auth
      .signIn(this.email, this.password)
      .then(() => this.$router.push({ name: "homeManagement" }))
      .catch((err: any) => (this.errorMessage = err.message))
      .finally(() => (this.loading = 0));
  }

Here is the test:

const $t = jest.fn();
$t.mockReturnValue("");

const $Auth = jest.fn();
$Auth.mockReturnValue({
  code: "UserNotFoundException",
  name: "UserNotFoundException",
  message: "User does not exist."
});


const factory = mountFactory(LoginForm, {
  mount: {
    mocks: {
      $Auth
    }
  }
});

describe("LoginForm", () => {
  it("User not found", async () => {
    const wrapper = factory();

    await wrapper.setData({
      email: "david@gmail.com",
      password: "Qwer321"
    });
    await wrapper.vm.signIn();
    expect(wrapper.vm.$data.errorMessage.length).not.toEqual(0);
  });
});

Solution

  • Figured out a solution, but maybe there is a better one flush-promises to mock Amplify call:

    const $Auth = jest.fn();
    $Auth.signIn = () => Promise.resolve();
    
    describe("LoginForm", () => {
    it("User does not exist", async () => {
    const wrapper = factory();
    
    await wrapper.setData({
      email: "david@gmail.com",
      password: "Qwer321",
      valid: true
    });
    
    await wrapper.vm.signIn();
    await flushPromises();
    expect(wrapper.vm.$data.errorMessage.length).not.toEqual(0);
      });
    });