【问题标题】:TypeError: state.customerComplaints.add is not a function in jest unit testTypeError:state.customerComplaints.add 不是开玩笑单元测试中的函数
【发布时间】:2021-09-13 13:11:22
【问题描述】:

我有一个简单的变异方法,可以将元素添加到我的集合中。现在我正在尝试测试该方法,并开玩笑抛出如下所述的错误。

//Vuex
const state = {
  customerComplaints : new Set()
};

// Mutation method
setCustomerComplaints(state, data) {
  state.customerComplaints.add(data);
}

//Error I am getting when running the test
//TypeError: state.customerComplaints.add is not a function

//Jest test
it('should do something', () => {
  const state = {
    customerComplaints: {}
  };
  myStore.mutations.setCustomerComplaints(state, 'UI issue');
  expect(state.customerComplaints).toBe('UI issue');
});

我试图模拟它,但我无法成功。请帮助我通过这个测试。

【问题讨论】:

    标签: vue.js jestjs vuex


    【解决方案1】:

    您的测试有一个不包含add 方法的本地state 对象,并且它将state 传递给尝试调用add 的变异方法,从而导致您观察到的错误。

    一个简单的解决方法是将您的本地 state.customerComplaints 初始化为 Set,就像您在实际的 Vuex 商店中所做的那样:

    it('should do something', () => {
      const state = {
        customerComplaints: new Set()
      };
      myStore.mutations.setCustomerComplaints(state, 'UI issue');
      //...
    });
    

    另外,要验证Set 是否包含项目,请使用toContain,而不是toBe

    // expect(state.customerComplaints).toBe('UI issue');
    expect(state.customerComplaints).toContain('UI issue');
    

    【讨论】:

      猜你喜欢
      • 2020-08-24
      • 1970-01-01
      • 2017-02-11
      • 2017-10-20
      • 2017-10-01
      • 2018-09-10
      • 1970-01-01
      • 2019-10-31
      • 1970-01-01
      相关资源
      最近更新 更多