Reputation: 508
I've a class having method implementation which takes the request params and returns the response object. I'm having issue while mocking the client request method. Can someone help me on this. Here is my service class and its test class.
Service.js
import Client from '/dist/client';
import urls from './urls';
import { NODE_ENV, API_VERSION } from '../constants';
const versionHeader = 'X-API-VERSION';
class ServiceClass extends Client {
getFiltersList(params) {
const config = {
method: urls.View.getFilters.requestType,
url: urls.View.getFilters.path(),
params,
headers: { [versionHeader]: API_VERSION },
};
return this.client.request(config);
}
}
Service.test.js
import Client from '/dist/client';
import urls from '../services/urls';
import { NODE_ENV, API_VERSION } from '../constants';
import filtersData from '../data/filters-data.json';
const versionHeader = 'X-API-VERSION';
import Service from '../services/Service';
describe('Service Class Test', () => {
it('Get List Test', () => {
const params = {
filters: 'abc,def,ghi',
};
let getListSpy;
const config = {
method: urls.View.getFilters.requestType,
url: urls.View.getFilters.path(),
params,
headers: { [versionHeader]: API_VERSION },
};
getListSpy = jest.spyOn(Service, 'this.client.request(config)');
getListSpy.mockReturnValue(filtersData);
expect(getListSpy).toHaveBeenCalledTimes(1);
expect(getListSpy).toEqual(filtersData);
});
});
Upvotes: 0
Views: 1932
Reputation: 1104
'this' refers to the class instance and could be private. With that being said the syntax would be
getListSpy = jest.spyOn(Service.client, 'request');
request(config) is a function call, not the actual function and config is a parameter being passed to the function.
Upvotes: 1