嘲笑类星体和打字稿

问题描述

我想在测试中模拟Amplify Auth服务。没有错误,但是由于我的模拟,测试无法正常工作。

这是我要测试的代码

  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));
  }

这是测试:

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);
  });
});

解决方法

想出了一个解决方案,但也许有更好的冲洗承诺来模拟Amplify调用:

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);
  });
});