Vue.JS单元测试 - 在使用sinon.stub()后仍然调用原始方法

Vue.JS单元测试 - 在使用sinon.stub()后仍然调用原始方法

问题描述:

我使用Sinon在单元测试我的组件(用TypeScript和vue-class-component编写)时存根API调用。在将单元添加到单元测试之后,仍然调用原始方法(不返回存根值)。Vue.JS单元测试 - 在使用sinon.stub()后仍然调用原始方法

it('should set the text to bar', async() => { 

    const stubbedApiResponse =() => { 
    return 'bar'; 
    }; 

    sinon.stub(MyComponent.prototype, 'getFoo').callsFake(stubbedApiResponse); 

    let options = { 
    template: '<div><my-component></my-component></div>', 
    components: {'my-component': MyComponent}, 
    store: this.store 
    }; 
    this.vm = new Vue(options).$mount(); 

    Vue.nextTick(() => { 
    expect(this.vm.$el.querySelector('.text').textContent).toBe('bar'); // Still equals 'foo' 
    }); 
}); 

,我试图存根呼吁在组件mounted和设置文本内容的方法。任何帮助将不胜感激,谢谢!

+0

你能提供调试分钟混帐回购协议? –

的问题是,使用与vue-class-component打字稿类时,该methods直播导出类的options属性里面的话,存根的方法,你必须做这样的:

sinon.stub(MyComponent.options.methods, 'getFoo').callsFake(stubbedApiResponse) 

在如果你的测试通过了这个改变,忽略下面的所有内容。


我看到一对夫妇的代码无关的问题:

  • 当使用PhantomJS,那么就使用async因为Vue.nextClick不会使用Promises反正也没点;这是简单的使用由摩卡提供的done功能:

    it('...', (done) => { 
        // ... 
        Vue.nextTick(() => { 
        // ... 
        done() 
        } 
    } 
    
  • 柴氏be是一个链,而不是测试平等;应使用equal,例如:expect(foo).to.equal('bar')

  • 这是更好地离开vm作为变量,而不是一个属性,以避免破坏参照头痛:

    const vm = //... 
    nextTick(() => { expect(vm.$el)//... } 
    
+0

我应该在第一篇文章中提到这个(除了标签),但我使用Typescript和Vue类组件装饰器,所以这些方法不在'methods'里面。它们只是该类的实例方法。 – cfly24

+0

更新的答案,考虑帐户打字稿类。 –