嗨,我正在尝试学习一些使用Express,Mocha,chai和johnny-five的测试驱动开发。所以我写了这个小应用程序,它可以打开和关闭LED。该应用程序可以运行,但是我的测试失败。有人可以告诉我测试中我做错了什么吗?
谢谢npm test
的输出是
> [email protected] test /Users/me/Documents/johnny-five/blink
> mocha --reporter spec
1435257445439 Looking for connected device
j5
.on()
1) Should turn a led on
.off()
✓ Should turn a led off
1 passing (13ms)
1 failing
1) j5 .on() Should turn a led on:
AssertionError: expected undefined to equal 1
at Context.<anonymous> (test/j5.js:9:14)
npm ERR! Test failed. See above for more details.
这是test / j5.js
require('mocha');
var assert = require('chai').assert;
var j5 = require("../j5");
describe('j5', function () {
describe('.on()', function () {
it('Should turn a led on',function(){
var result = j5.on();
assert.equal(result, 1);
});
});
describe('.off()', function () {
it('Should turn a led off', function () {
// var res = j5.on();
// expect(res).to.equal(0);
});
});
});
这是server.js
var express = require("express");
var app = express();
var j5 = require("./j5");
var port = 3000;
app.get('/', function(req, res){
res.send('hello j5');
});
app.get("/on", function(req, res) {
j5.on();
res.send("on");
});
app.get("/off", function(req, res) {
j5.off();
res.send("off");
});
console.log("listening on port http://localhost:" + port);
app.listen(3000);
这是j5.js
var exports = module.exports = {};
var five = require("johnny-five");
var board = new five.Board();
var board_ready = false;
var led = null;
board.on("ready", function() {
board_ready = true;
led = new five.Led(13);
});
exports.on = function() {
if (led !== null && board_ready === true) {
led.on();
return 1;
}
};
exports.off = function() {
if (led !== null && board_ready === true) {
led.off();
return 0;
}
};
编辑:test / j5.js中我的j5.js的路径错误。但现在我有一个新错误。 AssertionError:在上下文中预期未定义等于1。 (test / j5.js:9:14)。
最佳答案
经过一番游戏后,我发现了我的错误。
johnny-five需要一些时间通过串行连接到板。 REPL的内置版本一经提供,我就可以使用功能on()
和off()
。因此,我让测试等待5秒钟,然后再调用j5.on()
。 done()
函数的标准最大超时为2000ms。为了延长时间,我使用了this.timeout(10000);
这是我的新测试/j5.js
require('mocha');
var assert = require('chai').assert;
var j5 = require("../j5");
var result = null;
describe('j5', function() {
describe('.on()', function() {
it('Should turn a led on', function(done) {
this.timeout(10000);
setTimeout(function() {
result = j5.on();
assert.equal(result, 1);
done();
}, 5000);
});
});
});
npm test
的结果:> [email protected] test /Users/icke/Documents/johnny-five/blink
> mocha --reporter spec
1435305595110 Device(s) /dev/cu.usbmodem1421
1435305595124 Connected /dev/cu.usbmodem1421
j5
.on()
1435305598694 Repl Initialized
✓ Should turn a led on (5003ms)
.off()
✓ Should turn a led off
2 passing (5s)