gpt4 book ai didi

vue.js - 如何用 Jest 测试 catch 函数

转载 作者:行者123 更新时间:2023-12-05 06:32:01 28 4
gpt4 key购买 nike

如何从这样的函数中测试捕获:

getApi () {
const URL = '/api/division?key='
axios.get(URL)
.then((response) => {
this.counter = response.data
})
.catch(err => {
alert(err)
})
}

我正在使用 axios 和 vue js 来测试 JEST。希望任何解决方案,谢谢 :')

最佳答案

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

demo

关于vue.js - 如何用 Jest 测试 catch 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51553260/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com