【发布时间】:2021-09-05 05:20:10
【问题描述】:
我一直在尝试使用 jest.mock() 模拟我的 api,但我什至无法正常调用这些 api。
我已经能够成功地模拟函数,然后像这样模拟 api:
wrapper.vm.getUser = jest.fn(() => Promise.resolve({}));
但我想直接模拟api/authApis.js 中的所有api,而不是在函数中拦截它们。
我不能这样做,因为this.$apis 显示为未定义。
如何使用 Jest 访问和调用 this.$apis.getUser()?
测试/header.spec.js
import { mount } from "@vue/test-utils";
import Header from "../components/Header.vue";
describe("Header", () => {
it("returns the val from api", async () => {
//setting multiUser true so button is visible
const multiUsers = true;
const wrapper = mount(Header, {
propsData: {
multiUsers
}
});
console.log(wrapper.vm.getUser());
const changeUsrBtn = wrapper.find("#btnChangeUser");
//triggering the user btn with a click
changeUsrBtn.trigger("click");
expect(wrapper.find("button").text()).toBe("Change User");
expect(wrapper.vm.getUser()).toHaveReturned();
});
});
错误:
FAIL __tests__/header.spec.js
Header
× returns the val from api (122 ms)
● Header › returns the val from api
expect(received).toHaveReturned()
Matcher error: received value must be a mock function
Received has type: object
Received has value: {}
23 | expect(wrapper.find("button").text()).toBe("Change User");
24 |
> 25 | expect(wrapper.vm.getUser()).toHaveReturned();
| ^
26 |
27 | });
28 | });
at Object.<anonymous> (__tests__/header.spec.js:25:36)
at TestScheduler.scheduleTests (node_modules/@jest/core/build/TestScheduler.js:333:13)
at runJest (node_modules/@jest/core/build/runJest.js:387:19)
at _run10000 (node_modules/@jest/core/build/cli/index.js:408:7)
at runCLI (node_modules/@jest/core/build/cli/index.js:261:3)
console.error
TypeError: Cannot read property 'authService' of undefined
组件/Header.vue
async getUser() {
this.showUserLoader = true;
try {
const {
data: { userList }
} = await
this.$apis.authService.getUser();
this.$store.dispatch("auth/updateUsers", UserList);
} catch (error) {
console.error(error);
} finally {
this.showUserLoader = false;
}
}
...
api/authApis.js(我想模拟整个文件):
export default $axios => ({
getUser() {
return $axios({
url_instance: authInstance,
method: "get",
url_suffix: "/sc/typesOfUser",
});
},
changeUser() {
return $axios({
url_instance: authInstance,
method: "post",
url_suffix: "/sc/changeUser"
});
},
...
})
【问题讨论】:
-
我认为更重要的问题是您如何首先设置
this.$apis? :)
标签: javascript vue.js jestjs nuxt.js vue-test-utils