用 Quasar 和 Typescript 开玩笑
Jest Mocking with Quasar and Typescript
我想在我的测试中模拟 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);
});
});
找到了解决方案,但也许有更好的解决方案flush-promises来模拟 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);
});
});
我想在我的测试中模拟 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);
});
});
找到了解决方案,但也许有更好的解决方案flush-promises来模拟 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);
});
});