摩卡忽略了一些testing,尽pipe它们应该运行

我正在重构我的express-decorator NPM包的克隆。 这包括重构先前使用AVA进行的unit testing 。 我决定使用Mocha和Chai来重写它们,因为我喜欢他们定义testing的方式。

那么,我的问题是什么? 看看这个代码(我把它分解来说明问题):

test('express', (t) => { @web.basePath('/test') class Test { @web.get('/foo/:id') foo(request, response) { /* The test in question. */ t.is(parseInt(request.params.id), 5); response.send(); } } let app = express(); let controller = new Test(); web.register(app, controller); t.plan(1); return supertest(app) .get('/test/foo/5') .expect(200); }); 

此代码工作


这里(基本上)是相同的代码,现在使用Mocha和Chai和多个testing

 describe('The test express server', () => { @web.basePath('/test') class Test { @web.get('/foo/:id') foo(request, response) { /* The test in question. */ it('should pass TEST #1', () => expect(toInteger(request.params.id)).to.equal(5)) response.send() } } const app = express() const controller = new Test() web.register(app, controller) it('should pass TEST #2', (done) => { return chai.request(app) .get('/test/foo/5') .end((err, res) => { expect(err).to.be.null expect(res).to.have.status(200) done() }) }) }) 

问题TEST #1被摩卡忽略,尽pipe这部分代码在testing期间运行的。 我试图console.log那里,它出现在我期待它出现的摩卡日志。

那么我怎样才能让testing成功? 我的想法是以某种方式将上下文 (testing套件)传递给itfunction,但是对于Mocha来说这是不可能的,或者是这样吗?

看起来你正在从tape或一些类似的testing运动员到摩卡。 你将需要大大改变你的方法,因为摩卡的工作有很大的不同。

tape和类似的跑步者不需要事先知道套件中存在哪些testing。 他们在执行testing代码时发现testing,testing可以包含另一个testing。 另一方面,摩卡要求运行任何testing之前整个套件都是可发现的。*它需要知道套件中将存在的每一个testing。 它有一些缺点,在Mocha运行testing的时候你不能添加testing。 你不能有一个before钩子例如从数据库做一个查询,并从那个创buildtesting。 在套件启动之前,您应该执行查询。 但是,这种做事方式也有一些优点。 您可以使用--grep选项只selecttesting的一个子集,摩卡会毫不费力地完成。 您也可以使用it.only ,只select一个testing没有麻烦。 最后我检查了一下, tape和它的兄弟姐妹有这个麻烦。

所以你的摩卡代码不工作的原因是因为你正在摩卡开始运行testing之后创build一个testing。 摩卡不会对你崩溃,但当你这样做,你得到的行为是不确定的。 我见过摩卡会忽略新testing的情况,而且我也看到了以意外的顺序执行它的情况。

如果这是我的testing,我会做的是:

  1. foo删除it的呼叫。

  2. 修改foo来简单地logging我关心的控制器实例上的请求参数。

     foo(request, response) { // Remember to initialize this.requests in the constructor... this.requests.push(request); response.send() } 
  3. 有testingit("should pass test #2"检查logging在控制器上的请求:

     it('should pass TEST #2', (done) => { return chai.request(app) .get('/test/foo/5') .end((err, res) => { expect(err).to.be.null expect(res).to.have.status(200) expect(controler.requests).to.have.lengthOf(1); // etc... done() }) }) 
  4. 并使用beforeEach挂钩来重置testing之间的控制器,以便testing隔离。