TypeError: state.customerComplaints.add is not a function in jest unit test
TypeError: state.customerComplaints.add is not a function in jest unit test
我有一个简单的变异方法,可以将元素添加到我的集合中。现在我正在尝试测试该方法,并且 jest 抛出了如下所述的错误。
//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');
});
我试着模仿它,但我无法成功。请帮助我通过这个测试。
您的测试有一个不包含 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');
我有一个简单的变异方法,可以将元素添加到我的集合中。现在我正在尝试测试该方法,并且 jest 抛出了如下所述的错误。
//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');
});
我试着模仿它,但我无法成功。请帮助我通过这个测试。
您的测试有一个不包含 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');