[英]Unable to properly mock API calls using Jest
我一直在嘗試使用 jest.mock() 來模擬我的 api,但我什至無法開玩笑地正常調用這些 api。
我已經能夠成功模擬該函數,然后像這樣模擬 api:
wrapper.vm.getUser = jest.fn(() => Promise.resolve({}));
但我想直接模擬api/authApis.js
所有api/authApis.js
而不是在函數處攔截它們。
我不能這樣做,因為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.$api
,但如果你想模擬整個文件(尤其是使用默認導出),你應該使用__esModule
屬性:
jest.mock('./esModule', () => ({
__esModule: true, // this property makes it work
default: 'mockedDefaultExport',
namedExport: jest.fn(),
}));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.