执行多个摩卡测试
问题描述:
如果我有一组URL来访问:执行多个摩卡测试
let tests = [
{ status: 200, mediaType: 'text/html', req: { method: 'GET', uri: 'http://*.com/' } },
{ status: 200, mediaType: 'text/html', req: { method: 'GET', uri: 'http://*.com999/' } },
{ status: 200, mediaType: 'text/html', req: { method: 'GET999', uri: 'http://*.com/' } },
]
和一组测试对每个执行:
it('should have status ' + test.status,() => {
expect(test.response.statusCode).to.equal(test.status)
})
it('should have content type ' + test.mediaType,() => {
let s = test.response.headers['content-type']
let mediaType = s.indexOf(';') === -1 ? s : s.substr(0, s.indexOf(';'))
expect(mediaType).to.equal(test.mediaType)
})
it('should have a body',() => {
expect(test.body).to.not.equal('')
})
我怎样才能在每套测试中只执行一次昂贵的操作?另外,如果URL不加载,我不想运行测试。
答
mocha Working With Promises
documentation有一个例子,其中每个测试都等待一个beforeEach
承诺在执行之前完成。如果你需要一个beforeEach
反正,你可以保存为beforeEach
这个承诺,你可以让他们都等待一个承诺:
let P = null
beforeEach(function() {
if (!P) P = new Promise(...)
return P
})
但更可能的是,你只需要使用一个before
:
beforeEach(function() {
return new Promise(...)
})
对于这个问题的完整列表:
let expect = require('chai').expect
let request = require('request')
let tests = [
{ status: 200, mediaType: 'text/html', req: { method: 'GET', uri: 'http://localhost/' } },
{ status: 200, mediaType: 'text/html', req: { method: 'GET', uri: 'http://localhost999/' } },
{ status: 200, mediaType: 'text/html', req: { method: 'GET999', uri: 'http://localhost/' } },
]
tests.forEach(function (test) {
describe(test.req.method + ' ' + test.req.uri, function() {
before('should load', function() {
return new Promise(function (resolve, reject) {
request(test.req, function (error, response, body) {
if (error) {
reject(test.rejection = error)
} else {
test.response = response
test.body = response
resolve()
}
})
})
});
it('should have status ' + test.status,() => {
expect(test.response.statusCode).to.equal(test.status)
})
it('should have content type ' + test.mediaType,() => {
let s = test.response.headers['content-type']
let mediaType = s.indexOf(';') === -1 ? s : s.substr(0, s.indexOf(';'))
expect(mediaType).to.equal(test.mediaType)
})
it('should have a body',() => {
expect(test.body).to.not.equal('')
})
})
})
这给了你漂亮流利的输出:
GET http://*.com/
✓ should have status 200
✓ should have content type text/html
✓ should have a body
GET http://*.com999/
1) "before each" hook: should load for "should have status 200"
GET999 http://*.com/
✓ should have status 200
✓ should have content type text/html
✓ should have a body
如果你改变的例子使用计算器的本地主机这一翻译,你可以看访问日志,以验证每个URL被加载一次:
127.0.0.1 - - [21/Oct/2017:06:52:10 -0400] "GET/HTTP/1.1" 200 12482 "-" "-"
127.0.0.1 - - [21/Oct/2017:06:52:10 -0400] "GET999/HTTP/1.1" 501 485 "-" "-"
注意,最后的操作,GET999 http://*.com/
给出了一个200在*上(通过清漆缓存)和apache上的501:
2) GET999 http://localhost/
should have status 200:
AssertionError: expected 501 to equal 200
+ expected - actual
-501
+200
为什么不直接使用'before'? – shawon191
这确实比较好。我用'之前'更新了答案。 TX! – ericP