【问题标题】:spyOn question regarding function that return promise关于返回承诺的函数的 spyOn 问题
【发布时间】:2019-11-21 11:18:00
【问题描述】:

这是一个关于 spyOn 的相当普遍的问题,当使用在 Vue 组件中返回 Promise 的函数编写单元测试时。

我写测试的方式如下:

// Basically this function gets data from a service and sets some data in the component.
function getSomething() {
ServiceX.getSomething().then(response => 
this.x = response.x
)
}

测试:

describe('test', () => {
beforeEach() => {
vm = shallowMount(VueComponent)
spyOn(serviceX, 'getSomething).and.returnValue(promsie.resolve(data));
}

it('should set X', () =>{
vm.getSomething()
expect(vm.X).toBe(X);
})
}

问题是,当我以这种方式进行测试时,变量 X 尚未设置,但如果我执行“it”语句异步并等待 getSomething() 方法,它就可以工作。

我想知道是否有其他方法可以做到这一点。

【问题讨论】:

    标签: unit-testing vue.js jasmine spy


    【解决方案1】:

    因为您的原始方法返回了一个承诺,而您的间谍也返回了一个承诺(即使是已经解决的),您应该使用thenasync await,正如您在问题中评论的那样。

    所以,另一种做法是:

    it('should set X', (done) => {
        vm.getSomething().then(() => {
            expect(vm.X).toBe(X);
            done();
        });
    })
    

    使用 jasmine 中的done 参数通知此单元测试是异步的,将在调用此回调时完成。

    【讨论】:

      【解决方案2】:

      我知道这有点太晚了,您可能已经找到了解决方案,但如果您没有找到,我认为我将提出的解决方案对您有用。您可以使用 fakeAsync 和 tick 的组合来测试您的异步功能,下面是我的解决方案。

      describe('test', () => {
                   ...
                   it('should set X', fakeAsync(() =>{
                     vm.getSomething();
                     tick();
                     expect(vm.X).toBe(X);
                   }));
                   ...
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-03-18
        • 2017-04-05
        • 2019-01-23
        • 1970-01-01
        • 1970-01-01
        • 2020-05-23
        • 2022-01-26
        相关资源
        最近更新 更多