【问题标题】:Vue.JS Unit Testing - Original method is still being called after using sinon.stub()Vue.JS 单元测试 - 使用 sinon.stub() 后仍在调用原始方法
【发布时间】:2018-04-02 04:01:17
【问题描述】:

在对我的组件进行单元测试(使用 TypeScript 和 vue-class-component 编写)时,我使用 Sinon 来存根 API 调用。将存根添加到单元测试后,仍在调用原始方法(不返回存根值)。

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 上调用并设置文本内容。任何帮助将不胜感激,谢谢!

【问题讨论】:

  • 你能提供一个最小的 git repo 来调试吗?

标签: typescript vue.js karma-runner sinon sinon-chai


【解决方案1】:

问题在于,当使用带有 vue-class-component 的 TypeScript 类时,methods 存在于导出类的 options 属性中,因此,要存根方法,您必须这样做:

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

如果您的测试通过了更改,请忽略以下所有内容。


我在代码中看到了几个不相关的问题:

  • 当使用 PhantomJS 时,使用 async 毫无意义,因为 Vue.nextClick 无论如何都不会使用 Promises;使用mocha提供的done函数更简单:

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

  • 最好将vm 保留为变量而不是属性以避免引用问题:

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

【讨论】:

  • 我应该在最初的帖子中提到这一点(除了标签),但我使用的是 Typescript 和 Vue 类组件装饰器,所以这些方法不在 methods 中。它们只是类上的实例方法。
  • 更新的答案,考虑到打字稿类。
猜你喜欢
  • 2023-03-15
  • 1970-01-01
  • 2020-08-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多