How to mock api in jest and enzym

2019-09-02 15:28发布

This is the method which I use for making fetch calls to my api:

static sendJsonRequest(address, action, requestType, jsonData, queryParams, successCallback, errorCallback){

    var finalURL = Client.getServiceURL( address, action, queryParams);

    fetch(finalURL, {
      method: requestType,
      headers: {
        'content-type': 'application/json; charset=utf-8',
        'Authorization': 'Bearer ' + localStorage.getItem("access_token"),
        'pragma': 'no-cache',
        'cache-control': 'no-cache'
      },
      body: String(requestType).toLowerCase() === "get" ? undefined : JSON.stringify(jsonData)
    })
    .then(function(response) {
      if (!response.ok) {
          throw Error(response.statusText);
      }
      return response.json();
    })
    .then(function(jsonObj) {
      successCallback(jsonObj);
    })
    .catch(function(err) {
        errorCallback(err);
    });
}

And this is how I use this static method in my components:

        componentDidMount(){
            this.getPermissions();
        }

        getPermissions(){
            this.setState({
              Permissions_DATA: []
            });
            var permissionData = {userName: "xyz", resourceId : localStorage.getItem("target_resource_id")};
            Client.sendJsonRequest("authData", "getPermData", "POST", permissionData, "", this.handleGetPermissions, this.handleError);
          }

          handleGetPermissions(response){
            ---
          }

          handleError(e) {
             ---
          }

As as beginner I want to write test case for mocking this fetch call, but I don't know how to write the test cases for the same, can any one please help me out with this.

I tried googling out this as well, but not able to figured out anything. Thanks in advance

2条回答
smile是对你的礼貌
2楼-- · 2019-09-02 15:35

There is a library called Fetch Mock that will allow you to mock an API response for use in your tests.

An example of a test covering the behaviour of Client.sendJsonRequest might look something like:

test('Client.sendJsonRequest - calls API endpoint', (done) => {

    fetchMock.post('/the-url-to-test', { a mock response object... });
    Client.sendJsonRequest('/api/address', 'update', 'POST');
    expect(fetchMock.calls('/the-url-to-test').length).toBe(1);
});

The specific tests you will write depend on what you want to test, but the FetchMock documentation should help with that.

You'll be able to do things like check the success and error callbacks are fired, but using spies and stubs too.

查看更多
霸刀☆藐视天下
3楼-- · 2019-09-02 15:44

You can mock the whole function and tell it what exactly it should return.

jest.mock('../pathtoSendJsonRequest');

You have the possibility to mock async methods as well

查看更多
登录 后发表回答