【发布时间】:2020-09-22 07:17:25
【问题描述】:
我正在为 Vue 组件的方法编写 Jest 测试。具体来说,我想测试一个 Vuex 动作(我已经用mapActions 映射到组件中的这个动作)是用某个参数调用的。
我模拟了应该传递给动作的参数——我的测试很接近,但是动作接收到的参数有一堆额外的信息,我不知道为什么。
我正在测试的组件中的方法是:
triggerSave (trip) {
if (this.canSave) {
const tripToSave = { tripInProcess: true, trip: { tripId: trip.tripId, }, };
this.updateMyTrips(tripToSave);
}
},
updateMyTrips 是我在组件中映射到的 Vuex 操作。
在我的笑话测试中,我模拟了我在 beforeEach(以及商店)中测试的操作
describe('TripPlanner', () => {
let actions;
let store;
beforeEach(() => {
actions = {
updateMyTrips: jest.fn(),
},
store = new Vuex.Store({
modules: {
trips: {
namespaced: true,
actions,
},
},
});
});
我的测试本身是
test('trigger save calls updateMyTrips action', () => {
const mockTrip = [
{
tripId: 1234,
tripDestination: 'Rio di Janeiro',
},
];
const wrapper = shallowMount(TripPlanner, { store, localVue, propsData: { trip: mockTrip, canSave: true, }, },);
wrapper.vm.updateMyTrips(mockTrip[0]);
const mockUpdate = { tripInProcess: true, trip: { tripId: mockTrip.tripId }, };
expect(actions.updateMyTrips).toHaveBeenCalledWith(mockUpdate);
});
当我运行测试并查看 Expected/Received 值时,它确实收到了我的 mockUpdate 对象,但也收到了
"commit": [Function anonymous],
+ "dispatch": [Function anonymous],
+ "getters": Object {},
+ "rootGetters": Object {},
+ "rootState": Object {
+ "addOns": Object {},
+ "state": Object {},
所以测试失败了。
如果我只是测试 expect(actions.updateMyTrips).toHaveBeenCalled 测试通过...但是当我测试它是用该特定参数调用时,它会失败。
不明白为什么store的dispatch、getter、state等也被接收了!p>
【问题讨论】:
-
因为这是动作接收到的上下文对象的样子。
vm.updateMyTrips !== actions.updateMyTrips. -
啊,有道理....这个测试应该只是调用了动作。谢谢!
标签: jestjs vue-component vuex