首页 文章

使用Jest-React Native测试获取

提问于
浏览
0

我有一个常用的api类,用于处理React Native中的api调用 . 它将进行调用并获取json / error并返回它 . 请参阅下面的代码 .

// General api to acces data from web
import ApiConstants from './ApiConstants';
export default function api(path,params,method, sssid){

    let options;
        options = Object.assign({headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json'
        }},{ method: method }, params ? { body: JSON.stringify(params) } : null );


    return fetch(ApiConstants.BASE_URL+path, options).then( resp => {
        let json = resp.json();
        if (resp.ok) {
            return json;
        }
        return json.then(err => {
            throw err;
        }).then( json => json );
    });
}

但是当我在 tests 文件夹中编写模拟api的开玩笑测试时 .

test('Should login',() => {
    global.fetch = jest.fn(() => new Promise((resolve) => {
        resolve( { status: 201, json: () => (mock_data_login) });
    }));

    return Api(ApiConstants.LOGIN,{'un':'test1','pwd':'1234'},'post', null).then((data1)=>{

        expect(data1).toBeDefined();
        expect(data1.success).toEqual(true);
        expect(data1.message).toEqual('Login Success');
    });

});

它失败了:

TypeError:json.then不是函数

When I change the fetch return to this, the test passes:

return fetch(ApiConstants.BASE_URL+path, options).then( resp => {
            let json = resp.json();
            return json
        });
    }

为什么会出现此类型错误错误?我无法更改API模块,因为这将改变我的redux传奇代码 . 我该怎么办?

3 回答

  • 1

    在您的代码中,json只是一个Object而不是Promise,因此未定义 . 这是你得到的抱怨,因为你试图使用undefined作为一个函数 . 问题不在测试中,而是在您的代码中出现了错误 . 请尝试以下方法 .

    return fetch(ApiConstants.BASE_URL+path, options)
            .then(resp => resp.json())
            .then( json => json)
            .catch((error) => error);
        });
    
  • 0

    Edit: 哦,刚读过你不能对发生错误的组件进行更改?

    尝试像这样转换你的提取:

    return fetch(ApiConstants.BASE_URL+path, options)
    .then(resp => {
      let json = resp.json();
      if (resp.ok) {
        return json;
      } else {
        throw Error(resp.error) // assuming you have some kind of error from endpoint?
      }
    })
    .then(/*handle your ok response*/)
    .catch(/*handle your error response*/);
    
  • 1

    我遇到了同样的问题,问题是你只是在模拟response.json作为函数,但它应该是 Promise ,像这样,

    global.fetch = jest.fn(() => new Promise((resolve) => {
        resolve( { status: 201, json: () => {
             return Promise.resolve(mock_data_login);
           } 
        });
    }));
    

    这将为你的json函数返回一个Promise .

    希望这可以解决您的问题 .

相关问题