我是编写节点测试的新手....这是我尝试编写的gulp插件的第一个单元测试:
var chai = require('chai');
var spy = require('chai-spies');
var es = require('event-stream');
var File = require('vinyl');
var mock = require('mock-fs');
var sinon = require('sinon');
var sinonChai = require("sinon-chai");
//var rewire = require("rewire");
//var myModule = rewire("./test.js");
var es = require('event-stream');
chai.should();
chai.use(sinonChai);
describe('gulp-newy', function() {
var fs = require('fs');
var fakeFile, pspy;
beforeEach(function() {
//myModule.__set__('__dirname', "/home/one");
mock({
__dirname: mock.directory({
mode: 0755,
items: {
file1: 'file one content',
file2: new Buffer([8, 6, 7, 5, 3, 0, 9])
}
})
});
});
afterEach(mock.restore);
describe('get files', function() {
it('should do something', function(done) {
mock({
foo: mock.file({
content: 'nothing',
mtime: new Date(Date.now())
}),
bar: mock.file({
content: 'nothing',
mtime: new Date(1,1)
})
});
fakeFile = new File({
contents: new Buffer('foo'),
history: ['foo']
});
var bar = function(dest) { return 'bar' };
spy1 = sinon.spy(console, "log");
stream = newy(bar);
stream.write(fakeFile);
stream.on('data', function() {
console.log("sss");
});
spy1.should.have.been.called();
done();
});
});
});
我得到了TypeError: Attempted to wrap log which is already wrapped
,但是在我的间谍之前,我没有看到它之前被包裹的地方。
答案 0 :(得分:4)
我正在使用Mocha --watch ......哪个会话永远不会结束。因为这......另一个间谍存在。答案是Cleaning up sinon stubs easily
答案 1 :(得分:2)
对于sinon,您需要确保在每次测试后恢复存根\模拟。如果你不这样做,他们仍然是存根,如果你尝试在另一个测试中再次存根,它会大肆试图再次包装一个方法。 有很多方法可以做到这一点,包含沙箱中的所有存根,或者只是在“after”子句中进行恢复。 例如:
describe('This is a test', ()=> {
before(()=> {
sinon.stub(myObject,'myMethod', ()=> {
return 'stubbed result';
})
});
it('should stub my method', ()=>{
expect(myObject.myMethod).to.be.equal('stubbed result');
});
after(()=> {
//important part
myObject.myMethod.restore();
});
})