我试图在mocha中使用数据提供程序来编写更少的代码
var should = require('should');
var assert = require('assert');
var request = require('supertest');
var mongoose = require('mongoose');
var winston = require('winston');
var config = require('../app/config');
describe('Authentification', function() {
var url = config.web.protocol + '://' + config.web.host + ':' + config.web.port;
describe('signin',function()
{
var provider = [
{
describe: 'should return error trying to signin with empty body',
body: {},
status: 404,
message: "firstName not found"
},
{
describe: 'should return error trying to signin with no first name',
body: {
lastName: 'test',
password: 'test',
email: 'test'
},
status: 404,
message: "firstName not found"
},
{
describe: 'should return error trying to signin with no last name',
body: {
firtsName: 'test',
password: 'test',
email: 'test'
},
status: 404,
message: "lastName not found"
},
{
describe: 'should return error trying so signin with no password',
body: {
lastName: 'test',
firstName: 'test',
email: 'test'
},
status: 404,
message: "password not found"
},
{
describe: 'should return error trying so signin with no email',
body: {
lastName: 'test',
password: 'test',
firstName: 'test'
},
status: 404,
message: "email not found"
},
{
describe: 'should return error trying so signin a too long firstName',
body: {
firstName: 'kldsfjghsldkglsqkdjghqlkfjdsghldfksjghfdlskjgkldjfsdj',
lastName: 'test',
password: 'testhdksjdhfb',
email: 'test@aa.aa'
},
status: 400,
message: "invalid firstName"
},
];
for (var i in provider) {
it(provider[i].describe, function(done) {
request(url)
.post('/user/signin')
.send(provider[i].body)
.expect(provider[i].status)
.expect(function(res)
{
assert.equal(res.body.code, provider[i].status);
assert.equal(res.body.message, provider[i].message);
})
.end(done);
});
}
});
});
但在这种情况下,它只检查最后一次测试。
输出
Authentification
signin
✓ should return error trying to signin with empty body
✓ should return error trying to signin with no first name
✓ should return error trying to signin with no last name
✓ should return error trying so signin with no password
✓ should return error trying so signin with no email
✓ should return error trying so signin a too long firstName
6 passing (71ms)
但是如果最后一次测试失败,那么所有其他测试都会失败。如果其中一个测试错了,则测试通过。
可能存在异步问题,但我不知道如何解决它
答案 0 :(得分:9)
将for
循环更改为以下内容:
function makeTest(p) {
it(p.describe, function(done) {
request(url)
.post('/user/signin')
.send(p.body)
.expect(p.status)
.expect(function(res) {
assert.equal(res.body.code, p.status);
assert.equal(res.body.message, p.message);
})
.end(done);
});
}
for (var i in provider) {
makeTest(provider[i]);
}
您所拥有的代码存在的问题是您实际上只是在测试数组中的最后一个元素。 (是的,即使您看到不同的测试名称。)传递给it
的匿名函数将在未来的某个时刻执行,当时Mocha到达它。到那时你的循环将完成执行,i
的值将是循环给它的最后一个值。对it
提供的第一个参数不是问题,因为该参数是立即评估的。这就是为什么测试名称没问题,但测试本身只是测试数组中最后一个元素的多个实例。
上面的代码通过将provider[i]
传递给makeTest
来解决问题。当makeTest
中的匿名函数引用创建时使用的p
时,它具有调用makeTest
时使用的值。