0👍
✅
Methods are mocked the wrong way because they return functions. In order to be chainable, methods should return this
, this needs to be done without arrows:
{
then: jest.fn(function (usr) {
return this;
}),
fail: jest.fn(function (errors) { ... })
}
It doesn’t make sense to do wrapper.vm.$options.cachedUsers.push(response)
in mocked method because this is already done in original method.
fetchUserById
seems to return jQuery deferred, the result could be mocked with a deferred. The latter behaves similarly in most cases but requires to rename catch
to fail
. The problem with AddUserInfo
is that it doesn’t return a promise (deferred), which is an antipattern. It should be:
AddUserInfo(id){
return this.fetchUserById(id) ...
}
And:
const deferred = $.Deferred().resolve(mockUser);
wrapper.vm.fetchUserById = jest.fn().mockReturnValue(deferred);
wrapper.vm.AddUserInfo(user);
await deferred;
expect(wrapper.vm.$options.cachedUsers.length).toBe(1);
Source:stackexchange.com