我正在測試一些使用承諾chai-as-promised
和Mocha
的代碼。我的測試套件也利用fetch-mock來模擬通常使用Fetch API發送的AJAX請求。爲什麼這個chai-as-promised AssertionError打印到控制檯而不是我的摩卡測試運行器?
這裏有我想要的測試代碼:
/**
* Sends a POST request to save (either insert or update) the record
* @param {object} record simple object of column name to column value mappings
* @return {Promise} Resolves when the POST request full response has arrived.
* Rejects if the POST request's response contains an Authorization error.
*/
save(record) {
var _this = this;
return this._auth(record)
.then(function() {
return window.fetch(_this._getPostUrl(), {
method: 'post',
headers: {
'Content-type': 'application/x-www-form-urlencoded; charset=UTF-8'
},
body: _this._objToPostStr(record),
credentials: 'include'
});
})
.then(function(saveResp) {
return saveResp.text();
})
.then(function(saveResp) {
return new Promise(function(resolve, reject) {
if (saveResp.indexOf('Authorization') !== -1) {
reject('Request failed');
} else {
resolve(saveResp);
}
});
});
}
在我最上層describe
,我有這個功能最初設置了我fetchMock
對象。
before(() => {
fetchMock = new FetchMock({
theGlobal: window,
Response: window.Response,
Headers: window.Headers,
Blob: window.Blob,
debug: console.log
});
fetchMock.registerRoute({
name: 'auth',
matcher: /tlist_child_auth.html/,
response: {
body: 'authResp',
opts: {
status: 200
}
}
});
});
和這裏的相關測試代碼:
describe('save',() => {
it('save promise should reject if response contains the string Authorization',() => {
fetchMock.mock({
routes: ['auth', {
name: 'save',
matcher: /changesrecorded.white.html/,
response: {
body: 'Authorization',
opts: {
status: 200
}
}
}]
});
let _getLocationStub = sinon.stub(client, '_getLocation');
_getLocationStub.returns('/admin/home.html');
client.foreignKey = 12345;
let promise = client.save({
foo: 'bar'
});
promise.should.eventually.be.fulfilled;
fetchMock.unregisterRoute('save');
});
});
我定義的fetchMock.mock()
呼叫save
路線是我需要的save
路線另一個測試,以重新定義返回的東西的原因其他。
爲了確保chai-as-promise實際工作正常,並會通知我失敗的測試,我寫了一個失敗的測試promise.should.eventually.be.fulfilled;
。這將失敗,因爲save
返回的承諾將拒絕如果響應包含Authorization
,它會這樣做。 Chrome控制檯顯示message: expected promise to be fulfilled but it was rejected with 'Request failed
AssertionError,但我的摩卡test-runner.html
頁面顯示此測試通過。出於某種原因,chai-as-promise沒有與Mocha正確溝通。
如果您希望看到我的整個項目,請參閱Github上的this repo。
任何想法爲什麼?
編輯:
這裏是我的測試設置代碼:
let expect = chai.expect;
mocha.setup('bdd');
chai.should();
chai.use(chaiAsPromised);
似乎很明顯,文檔在閱讀本文後一直這樣說。謝謝你的回答! –