简体   繁体   中英

How to mock a method which returns response object using Jest

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);

  });

});

'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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM