我已经成功地在一个简单的应用程序上测试了一个已解决的承诺,我一直在努力学习ES6,但一直在测试可能存在网络错误的情况。如何测试抓取api中的网络错误?
我写这个测试用例:
import {Weather} from '../js/weather';
import chai from 'chai';
import sinon from 'sinon';
import * as chaiAsPromised from 'chai-as-promised';
chai.use(chaiAsPromised);
let assert = chai.assert;
let should = chai.should;
describe('weatherbot-1', function() {
beforeEach(function() {
sinon.stub(window, 'fetch');
let data = '{"cod": "400", "message": "Nothing to geocode"}';
let res = new window.Response(data, {
ok: false,
status: 400,
headers: {
'Content-type': 'application/json'
}
});
window.fetch.returns(Promise.reject(res));
});
afterEach(function() {
window.fetch.restore();
});
it('should ensure that promise is rejected', function() {
let weather = new Weather(0, 0);
return assert.isRejected(weather.getWeather(), 'Rejected');
});
});
问题的方法是:
getWeather() {
let headers = new Headers();
let init = {
method: 'GET',
headers: headers,
cache: 'default'
};
let url = 'http://localhost:8080/weather?lat=' + '' + '&lon=' + this.longitude;
return fetch(url, init).then(function (response) {
return response.json();
}).catch((error) => {
return error;
});
}
为了测试的承诺,我使用chai-as-promised
& chai
与mocha
& sinon
存根的fetch
API 。
每当我运行测试我得到这个错误:
AssertionError: expected promise to be rejected with an error including 'Rejected' but it was fulfilled with { type: 'default',
url: '',
redirected: false,
status: 400,
ok: false,
statusText: 'OK',
headers:
{ append: [Function: append],
delete: [Function: delete],
get: [Function: get],
getAll: [Function: getAll],
has: [Function: has],
set: [Function: set],
keys: [Function: keys],
values: [Function: values],
entries: [Function: entries],
forEach: [Function: forEach] },
body: {},
bodyUsed: false,
clone: [Function: clone],
arrayBuffer: [Function: arrayBuffer],
blob: [Function: blob],
json: [Function: json],
text: [Function: text] }
从什么样子,在Promise.reject()
可能无法正常工作。有没有其他方法可以测试网络错误?
感谢您的回答,我删除了'catch',但我得到一个新的错误:在Object.compatibleMessage(测试/ rejectedPromise.js无法读取属性未定义 \t“的indexOf”: '类型错误825 :254) \t at test/rejectedPromise.js:8036:1432 \t at' –
thedeliciousmuffin
这听起来像是'assert.isRejected'中的一个错误。我期望它假定拒绝值是一个带有'message'属性的'Error'。如果您向拒绝中添加“讯息”,错误是否会消失?我知道这不会是一个代表'fetch'拒绝,但它会帮助诊断问题。 – joews
事实上,读取你的代码更多 - Promise不会拒绝'fetch'。 'fetch'返回一个已解析的Promise,用于非200错误代码的有效HTTP响应。 – joews