【发布时间】:2022-01-20 12:28:47
【问题描述】:
我正在尝试测试一个在安装时异步加载数据的组件。该组件按预期工作,只是给我带来问题的测试。组件的 async loadData() 函数在 await axios.get() 处挂起,而 jest 测试运行程序位于 component.vm.$nextTick() 中。因此,$nextTick 循环中的检查永远不会通过。
$nextTick 循环超时后,组件的 await 语句立即完成并且组件呈现自身。 axios 被嘲笑,所以它应该很快解决。如果我删除 await 并只填写一个常量,整个事情就会按预期执行。
我猜 $nextTick 循环不是异步的,它正在消耗线程,尽管这是测试异步内容的推荐方法。问题是,我没有等待的 onclick 异步处理程序:此方法是从 onMount 调用的。
不幸的是,我不知道如何制作这个的jsFiddle,所以我希望这就足够了:
我的组件(相关部分)
export default {
data() { return { content: '' }; },
mounted() { this.loadDoc() }
methods: {
async loadDoc() {
const res = await axios.get('some url'); // <-- this is the line that hangs until timeout
// const res = { data: 'test data'}; // this would test just fine
this.content = res.data;
}
}
}
还有我的 component.spec.js:
jest.mock('axios', () => ({
get: async (url) => {
return { data: 'test data' };
}
};
describe('my super test', () => {
it('renders', (done) => {
const doc = shallowMount(myComponent);
doc.vm.$nextTick(() => {
expect(doc.html()).toContain('test data'); // <-- this never matches
done();
});
});
});
【问题讨论】:
标签: jestjs vue-component vue-test-utils