好的,首先在应用程序的根目录下创建测试文件夹。添加您喜欢的任何类型的文件夹结构...这是我的一个项目的屏幕截图:
我使用 supertest 并且应该...因此,如果您想复制粘贴我将在此处输入的内容,请安装(当然还有 mocha):
npm install supertest
npm install should
接下来,在 bootstrap.test.js 内部(例如查看上图以查看放置位置)添加如下配置:
var Sails = require('sails');
before(function (done) {
process.env.NODE_ENV = 'test';
process.env.PORT = 9999;
Sails.lift({
models: {
connection: 'localDiskDb',
migrate: 'drop'
}
}, function (err, server) {
sails = server;
if (err) return done(err);
sails.log.info('***** Starting tests... *****');
console.log('\n');
done(null, sails);
});
});
after(function (done) {
sails.lower(done);
});
现在,添加您的第一个测试...在您的示例中,我会将其放在 test/integration/controllers/MyController.test.js 中
这是您可以用于测试的演示代码:
var request = require('supertest'),
should = require('should');
describe('My controller', function () {
before(function (done) {
done(null, sails);
});
it('should get data', function (done) {
request(sails.hooks.http.app)
.get('/list/item')
.send({id: 123, someOtherParam: "something"})
.expect(200)
.end(function (err, res) {
if (err) return done(err);
should.exist(res.body);
done();
});
});
});
现在,打开 mocha.opts 文件(如果您感到困惑,请查看上面的屏幕截图)并添加如下内容:
--bail
--timeout 20s
test/bootstrap.test.js
test/integration/controllers/**/*.test.js
最后,在你的根文件夹中的终端中输入 mocha 来运行测试!
你也可以像这样向 package.json 添加脚本:
"scripts": {
"test": "mocha"
},
然后简单地运行:npm test