【问题标题】:Jest Testing in VueVue 中的笑话测试
【发布时间】:2020-12-15 17:39:27
【问题描述】:

如何使用 Jest Test 来测试这个方法:

  delayedFetch() {
  setTimeout(() => {
    this.fetchData();
  }, 1000);

我尝试过使用 Async 和 await,但我很可能使用错了。

【问题讨论】:

    标签: vue.js jestjs


    【解决方案1】:

    很难测试带有副作用的代码,而且您没有提供完整的上下文,但我会尽力提供帮助。

    我认为setTimeout 内的this.fetchData() 中的this 引用了delayedFetch 方法本身。 (我不知道这是你的意图,至于我如何使用 vue.js

    但无论如何你都可以在这里找到如何测试 setTimeouts link to jest doc

    这是一个简单的实现

    const someObj = {
      // I assume the delayedFetch is some method of an object
      fetchData() {
        return "some-data";
      },
      delayedFetch() {
        const vue = this;
        setTimeout(() => {
          vue.fetchData();
        }, 1000);
      }
    }
    
    jest.useFakeTimers();
    
    test("delayedFetchTest", () => {
      someObj.delayedFetch();
    
      expect(setTimeout).toHaveBeenCalledTimes(1);
      expect(setTimeout).toHaveBeenLastCalledWith(expect.any(Function), 1000);
    })
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-08-27
      • 2018-08-09
      • 2019-09-06
      • 2020-02-06
      • 2019-04-18
      • 2019-07-05
      • 2019-08-17
      • 2021-06-13
      相关资源
      最近更新 更多