我正在尝试在2个mocha测试文件之间连接对象。这是我的test1.js文件,一旦所有测试用例都被执行,它应该导出一个变量。
var assert = require('assert');
var newUser = {
email: "test@ex.com",
name: "test@ex.com",
password: "test@ex.com",
confirmPassword: "test@ex.com"
}
var studentAcademicData = {
marks: {},
activities: {}
}
var studentInterests = []
var testSummary = {},
loggedInUser = {},
avaialbleAssessment = {},
test = {},
interests = {};
var studentAcademicId, studentId, academicYearId, assessmentId, testId;
describe('perform functional Test', function() {
before(function() {
this.timeout(15000);
db.init(config.mongodb);
})
//Register a student it ('Register a student', function(done){
StudentController.register(newUser).then(function(data) {
assert.equal(data.name, newUser.name) assert.equal(data.tenant, newUser.tenant) assert.equal(data.customerType, newUser.customerType)
done();
}).catch(done)
});
//User authentication it ('Authenticates user', function(done){
var userInfo = {
appId: "abc",
email: newUser.email,
password: newUser.password
}
security.userAuthenticate(userInfo).then(function(data) {
securityToken = data.securityToken;
tenantId = data.tenantId;
emailStatus = data.emailStatus;
mobileStatus = data.mobileStatus studentId = data.userId;
done();
}).catch(done)
});
it('Gets Student by id', function(done) {
StudentController.getById(studentId).then(function(data) {
loggedInUser = data;
loggedInUser.tenantId = 'abc';
loggedInUser.userId = studentId;
loggedInUser.securityToken = securityToken;
done();
}).catch(done)
});
})
module.exports.testUser = {
loggedInUser: loggedInUser,
avaialbleAssessment: avaialbleAssessment,
interests: interests,
testSummary: testSummary,
studentAcademicData: studentAcademicData,
newUs
er: newUser,
test: test
};
这是我的test2.file,它从test1.js文件中导入对象
var assert = require('assert');
var rewire = require('rewire');
var TestUserObj = require('./test1');
describe('perform test2 Test', function() {
console.log("in test2")
console.log("TestUserObj ::::" + JSON.stringify(TestUserObj))
});
我在test2.js文件中输入的输出是
TestUserObj
::::{
"testUser": {
"loggedInUser": {},
"avaialbleAssessment": {},
"interests": {},
"testSummary": {},
"newUser": {
email: "test@ex.com",
name: "test@ex.com",
password: "test@ex.com",
confirmPassword: "test@ex.com"
},
"test": {}
}
}
导出的值不包含修改后的对象
答案 0 :(得分:2)
正如@sheplu在评论中提到的那样,单元测试中的测试文件应该是分开的。事实上,每个被测试的单元应独立于其他单元。
您要寻找的是buildup
和teardown
系统,或fixtures
。
基本上,您需要确保在运行一组测试之前已经设置了所需的项目。
before()
和/或beforeEach()
hooks来执行此操作mockgoose
提供了一个很好的包来模拟内存中的测试数据库完成测试用例后,您还应注意:
after()
和/或afterEach()
hooks 您还可以查看supertest
以在测试用例中进行API请求调用。
在第二个文件中执行上述操作将确保您始终拥有一组可用的数据,以便在特定测试套件中运行测试。