vue.js - 如何用 Jest 测试 catch 函数
问题描述
如何从这样的函数中测试捕获:
getApi () {
const URL = '/api/division?key='
axios.get(URL)
.then((response) => {
this.counter = response.data
})
.catch(err => {
alert(err)
})
}
我正在使用 axios 和 vue js 来测试 JEST。希望有任何解决方案,谢谢:')
解决方案
Try axios-mock-adapter
,它可以模拟axios.get()
调用的结果,允许您模拟特定请求的网络错误/超时(从而catch
在代码中调用回调):
import axios from "axios";
import MockAdapter from "axios-mock-adapter";
const mock = new MockAdapter(axios);
mock.onGet(`/* URL used by component */`).networkError();
示例单元测试getApi()
:
it("does not modify username from network error", async () => {
mock.onGet(`/* URL used by component */`).networkError();
await wrapper.vm.getApi();
expect(wrapper.vm.username).toBe(INIT_USERNAME);
});
it("does not modify username from network timeout", async () => {
mock.onGet(`/* URL used by component */`).timeout();
await wrapper.vm.getApi();
expect(wrapper.vm.username).toBe(INIT_USERNAME);
});
推荐阅读
- c++ - 如何终止 DLL 中的 log4cplus?
- python - 使用 tcsh 包装器收集 python 覆盖
- function - 更改整个 react-native 应用程序的语言
- swift - 如何使用swift在Macosx App中执行launchctl load start?
- javascript - 当我单击它时,Framework 7 Accordion 不显示,我知道问题出在 JS 文件上吗?
- arrays - 如果条件满足,Arrayformula 获取上述单元格的值
- python - 使用 pytorch 对给定张量进行洗牌的矢量化方法
- sql - 在 PostgresSQL 和 Oracle 中,具有多个 OR 的 where 条件下的 4000 个输入会影响查询性能
- windows - 见证客户端注册见证服务器失败
- c - 64 位和 32 位定点数之间的转换