在完成我的IT项目后,我尝试添加一些单元测试,因为它符合规范(是的,我知道这在技术上是错误的顺序)。为此,我使用mocha
,结合chai
,chai-http
和sinon
。一切顺利,直到我在测试路由时尝试删除我的数据库文件bin\database.js
。这是数据库文件的最小工作示例:
/* jshint esversion: 6, node: true */
'use strict';
console.log('loaded'); // For verifying that the cache doesn't work
function def(some, callback) {
callback();
}
function defArray(some, callback) {
callback(undefined, []);
}
function defNumber(some, callback) {
callback(undefined, 0);
}
module.exports = {
Category: function() {},
addCategory: def,
modifyCategory: def,
removeCategory: def,
getCategories: defArray,
getCategory: def,
countCategories: defNumber,
Question: function() {},
addQuestion: def,
modifyQuestion: def,
answeredQuestion: def,
removeQuestion: def,
getQuestions: defArray,
getQuestion: def,
countQuestions: defNumber,
Highscore: function() {},
addHighscore: def,
removeHighscore: def,
getHighscores: defArray,
highscoreSort(a, b) {
return a.name < b.name ? -1 : 1;
},
countHighscores: defNumber
};
使用sinon的代码如下所示:
before(function() {
sinon.stub(database, 'getCategories', function(filter, callback) {
setTimeout(function() {
console.log('getCategories');
callback(null, []);
}, 30);
});
sinon.stub(database, 'getQuestions', function(filter, callback) {
setTimeout(function() {
console.log('getQuestions');
callback(null, []);
}, 30);
});
});
afterEach(function() {
database.getCategories.reset();
database.getQuestions.reset();
});
after(function() {
database.getCategories.restore();
database.getQuestions.restore();
});
如果我现在使用set NODE_ENV=testing & mocha --watch
运行mocha测试(测试文件是test \ test-routes.js,请不要介意env变量,这样可以减少杂乱控制台),它在第一次运行时工作正常,打印&#34; getQuestions&#34;和&#34; getCategories&#34;得到它的地方:
routes
admin route
GET requests
√ should redirect from /admin to /admin/home (542ms)
√ answers correctly on GET to/admin/home (231ms)
getCategories
√ answers correctly on GET to/admin/category (696ms)
getCategories
getQuestions
√ answers correctly on GET to/admin/question (584ms)
√ answers correctly on GET to/admin/highscore (299ms)
但是,当我在测试文件中更改了某些内容后--watch
进入时,输出中缺少这些内容。此外,这似乎是唯一没有缓存的文件,经验证如下:
console.log(Object.keys(require.cache).length);
var database = require('../bin/database');
console.log(Object.keys(require.cache).length);
var server = require('../bin/www');
var chai = require('chai');
var chaiHTTP = require('chai-http');
var expect = chai.expect;
var sinon = require('sinon');
console.log(Object.keys(require.cache).length);
第一次打印72
,73
和354
。在进一步调用时,它会打印539
,540
和540
,表明bin\database.js
没有被缓存。
任何人都可以提供有关可能导致此行为的进一步见解吗?我不会在任何其他文件中手动清除缓存,这是唯一要执行此操作的文件。
我正在使用mocha 3.1.2,sinon 1.17.6和chai 3.5.0运行节点v6.8.1。