如何在玩笑和酶中模拟api [英] How to mock api in jest and enzym

查看:92
本文介绍了如何在玩笑和酶中模拟api的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我用来对api进行调用的方法:

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) {
             ---
          }

作为初学者,我想编写用于模拟此fetch调用的测试用例,但我不知道如何编写相同的测试用例,请问有人可以帮我解决这个问题.

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

推荐答案

有一个名为 Fetch Mock的库,它允许您模拟一个API响应以供您在测试中使用.

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

一个涵盖Client.sendJsonRequest行为的测试示例可能类似于:

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

您将编写的特定测试取决于您要测试的内容,但是FetchMock文档应对此提供帮助.

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.

这篇关于如何在玩笑和酶中模拟api的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆