2021年3月2日星期二

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);      });    });  
https://stackoverflow.com/questions/66451536/how-to-mock-a-method-which-returns-response-object-using-jest March 03, 2021 at 01:56PM

没有评论:

发表评论