我很想测试一些将 Promises 与chai-as-promised
and结合使用的代码Mocha
。我的测试套件还利用fetch-mock来模拟通常使用 Fetch API 发送的 AJAX 请求。
这是我要测试的代码:
/**
* 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');
});
});
我在调用中定义save
路由的原因fetchMock.mock()
是我有另一个测试需要save
重新定义路由以返回其他内容。
为了确保 chai-as-promised 确实有效并且会通知我测试失败,我写了一个失败的测试promise.should.eventually.be.fulfilled;
。save
这将失败,因为如果响应包含,则返回的 Promise将拒绝Authorization
,它确实如此。Chrome 控制台显示 AssertionError message: expected promise to be fulfilled but it was rejected with 'Request failed
,但我的 Mochatest-runner.html
页面显示此测试通过。出于某种原因,chai-as-promised 无法与 Mocha 正确通信。
如果你想看我的整个项目,请在 Github 上查看这个 repo 。
任何想法为什么?
编辑:
这是我的测试设置代码:
let expect = chai.expect;
mocha.setup('bdd');
chai.should();
chai.use(chaiAsPromised);