Nat*_*nes 3 javascript unit-testing mocha.js chai-as-promised
我tyring测试使用的承诺与一些代码chai-as-promised
和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);
}
});
});
}
Run Code Online (Sandbox Code Playgroud)
在我的最上层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
}
}
});
});
Run Code Online (Sandbox Code Playgroud)
这是相关的测试代码:
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');
});
});
Run Code Online (Sandbox Code Playgroud)
我save
在fetchMock.mock()
调用中定义路由的原因是我有另一个测试需要save
重新定义路由以返回其他内容。
为了确保 chai-as-promised 实际工作并通知我失败的测试,我写了一个失败的 test promise.should.eventually.be.fulfilled;
。这将失败,因为save
如果响应包含Authorization
,则返回的 Promise将拒绝,它确实如此。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);
Run Code Online (Sandbox Code Playgroud)
该值promise.should.eventually.be.fulfilled
是一个承诺,您应该返回该承诺,以便 Mocha 可以知道您的测试何时结束。我创建了一个小的测试文件来模拟您所看到的内容,如果像您一样,我只是无法返回,我可以完全复制该行为promise.should.eventually.be.fulfilled;
。这是一个有效的示例:
import chai from "chai";
import chaiAsPromised from "chai-as-promised";
chai.use(chaiAsPromised);
chai.should();
describe("foo", () => {
it("bar", () => {
let promise = Promise.reject(new Error());
return promise.should.eventually.be.fulfilled;
});
});
Run Code Online (Sandbox Code Playgroud)
在你的代码有一些清理代码在测试的最后:fetchMock.unregisterRoute('save');
。根据您展示的内容,我after
会将其移动到一个钩子上,以便它反映您的before
钩子。通常,after
应该执行与 inbefore
和inafterEach
中的内容相对应的清理beforeEach
。但是,如果出于某种原因需要在测试中包含清理代码,则可以执行以下操作:
function cleanup() {
console.log("cleanup");
}
return promise.should.eventually.be.fulfilled.then(
// Called if there is no error, ie. if the promise was
// fullfilled.
cleanup,
// Called if there is an error, ie. if the promise was
// rejected.
(err) => { cleanup(); if (err) throw err; });
Run Code Online (Sandbox Code Playgroud)
不幸的是,Chai 似乎返回了一些看起来像 ES6Promise
但只是部分的东西。最终,它可能会返回一个实际的 ES6 承诺,然后.finally
无论发生什么,您都可以调用运行清理代码并自动传播错误。