您好我在尝试使用express,mocha,chai和johnny-five来学习一些测试驱动开发。所以我写了这个小应用程序,可以打开和关闭LED。应用程序工作,但我的测试失败。有人可以告诉我在测试中我做错了什么吗? 谢谢
npm test
的输出是
> blink@1.0.0 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:在Context上预期undefined等于1。 (试验/ j5.js:9:14)。
答案 0 :(得分:1)
经过一番游戏,我发现了自己的错误
johnny-five需要一些时间通过串口连接到电路板。只要REPL中的构建可用,我就可以使用函数on()
和off()
。所以我在进行j5.on()
调用之前等待了5秒。 done()
函数的标准最大超时为2000毫秒。为了延长这段时间,我使用了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
的结果:
> blink@1.0.0 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)