我有一个通用的 api 类,用于处理 React Native 中的 api 调用。它将进行调用并获取 json/ 错误并返回它。请参阅下面的代码。
// 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 );
});
}
但是,当我编写笑话测试来模拟 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 不是函数
当我将获取返回更改为此时,测试通过:
return fetch(ApiConstants.BASE_URL+path, options).then( resp => {
let json = resp.json();
return json
});
}
为什么会弹出这种类型的错误错误?我无法更改 API 模块,因为那将更改我的 redux saga 代码。我应该怎么办?