Reputation: 2265
I need to create unit test for the following prototype method validateAddress
:
import MyService from 'api/my-service';
import staticData from 'static-data';
import constants from 'utilities/constants';
import locale from 'api/locale-provider';
const myService = new MyService();
/**
* @param {Object} values
* @param {String} currency
* @param {Object} userProfile
* @returns {Promise<boolean>}
*/
export const validateAddress = (
values,
currency,
userProfile
) => {
const countryCode = locale.getCountry();
if (
staticData.type === constants.BILLING_MANAGER &&
(countryCode === 'CA' || countryCode === 'US')
) {
const payload = makeAddressPayload({
values,
currency
});
return myService
.postAddress(payload, userProfile)
.then(() => {
return true;
})
.catch(() => {
return false;
});
}
return true;
};
const makeAddressPayload = ({
values,
paymentProcessor,
currency
}) => ({
...
});
Does anyone know how I can mock MyService
class method postAddress
?
class MyService {
constructor(options = {}) {
...
}
postAddress(payload, userProfile) {
let promise = authorizedFetchRequest(
...
);
promise = fetchTimeoutHandler(promise);
return promise;
}
}
export default MyService;
Upvotes: 0
Views: 239
Reputation: 2265
I took suggestion from wentjun and ended up implementing it as such:
const spy = jest
.spyOn(MyService.prototype, 'postAddress')
.mockImplementationOnce(() => {
return new Promise(resolve => {
resolve(fixtures.addressPostSuccess);
});
});
And if I wanted to mock failure:
const spy = jest
.spyOn(MyService.prototype, 'postAddress')
.mockImplementationOnce(() => {
return new Promise((resolve, error) => {
error(fixtures.addressPostFailure);
});
});
Upvotes: 0
Reputation: 42526
For your case, you can use the mockImplementationOnce method to mock the response for postAddress
request.
This is how you can spy on it as part of your test,
it('should call postAddress', () => {
jest.spyOn(MyService, 'postAddress').mockImplementationOnce(() => (
...expected response
));
});
Upvotes: 1