【问题标题】:Vue component doing async hangs at await while jest testing在开玩笑测试时,执行异步的 Vue 组件在等待时挂起
【发布时间】: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


    【解决方案1】:

    我会删除,但我只是花了相当多的时间来完成文档中建议的内容,但没有解释这是唯一的方法......我希望其他人觉得这很有用。

    使用 flush-promises 包而不是 $nextTick 循环立即“修复”了问题

    代码示例(以上返工):

    describe('my super test', () => {
      it('renders', async() => {
        const doc = shallowMount(myComponent);
        await flushPromises();
        expect(doc.html()).toContain('test data'); // <-- now it works
      });
    });
    

    【讨论】:

      猜你喜欢
      • 2023-02-09
      • 1970-01-01
      • 2019-06-30
      • 1970-01-01
      • 2018-06-11
      • 1970-01-01
      • 2022-01-13
      • 2020-09-01
      • 2022-01-01
      相关资源
      最近更新 更多