我是Mocha的新手,我希望有人可以帮助我。我很好奇如何确保在一次测试中执行的操作不会影响另一次测试。例如,假设我有一个函数microbe
,它返回一个看起来像这样的对象:
{
_state : {
views : 'views'
}
set : function(key, val) { this._state[key] = val }
}
这是我正在使用的主要缩减版本,但它使用测试套件演示了我正在测试的内容,例如:
var expect = require('chai').expect;
describe('State', function() {
var microbe = require('../microbe/index'), app;
beforeEach(function(done) {
app = microbe();
});
it('should update the view location with app.set', function() {
app.set('views', 'test');
expect(app._state.views).to.equal('test');
});
it('should return "views" as the defualt view location', function() {
expect(app._state.views).to.equal('views');
});
});
第二次测试失败,因为第一次测试将app._state.views
设置为'test'
,因此它会覆盖默认值'views'
。我以为Mocha会隔离每个测试,但显然不是。我试图仅使用beforeEach
为每个测试重新实例化应用程序,但它似乎仍然是漏洞。
这是最好的方法吗?我知道我可以颠倒测试的顺序,它在技术上会通过,但我宁愿解决问题本身而不是避免它
答案 0 :(得分:0)
我刚刚测试了您发布的代码并且测试运行正确:
test.js:
var expect = require('chai').expect;
describe('State', function() {
var microbe = require('./microbe.js'), app;
beforeEach(function() {
app = microbe();
});
it('should update the view location with app.set', function() {
app.set('views', 'test');
expect(app._state.views).to.equal('test');
});
it('should return "views" as the defualt view location', function() {
expect(app._state.views).to.equal('views');
});
});
microbe.js:
module.exports = function () {
return {
_state : {
views : 'views'
},
set : function(key, val) { this._state[key] = val; }
};
};
执行mocha输出:
/tmp mocha -R spec test.js
State
✓ should update the view location with app.set
✓ should return "views" as the defualt view location
2 passing (5ms)
你的实现中有一些奇怪的东西(可能是某个地方的单例或全局变量),但它并不是摩卡的错误。