【问题标题】:Mocha ignores some tests although they should be runMocha 忽略了一些测试,尽管它们应该运行
【发布时间】:2018-02-09 18:14:42
【问题描述】:

我正在正确地重构我的express-decorator NPM 包的克隆。这包括重构之前使用AVA 完成的the unit tests。我决定使用MochaChai 重写它们,因为我更喜欢它们定义测试的方式。

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

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 以及多个测试

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 被 Mocha 忽略了,尽管这部分代码在测试期间运行。我尝试在那里console.log 一些东西,它出现在我希望它出现的摩卡日志中。

那么我如何让该测试发挥作用?我的想法是以某种方式将上下文(测试套件)传递给it 函数,但对于 Mocha,这是不可能的,不是吗?

【问题讨论】:

    标签: node.js unit-testing typescript mocha.js chai


    【解决方案1】:

    您似乎正在从 tape 或一些类似的测试运行程序转移到 Mocha。您将需要显着改变您的方法,因为 Mocha 的工作方式大不相同。

    tape 和类似的跑步者不需要提前知道套件中存在哪些测试。他们在执行您的测试代码时发现测试,并且一个测试可以包含另一个测试。另一方面,Mocha 要求整个套件在运行任何测试之前 是可发现的。* 它需要知道您的套件中将存在的每一个测试。它有一些缺点,即您无法在 Mocha 运行测试时添加测试。例如,您不能使用before 钩子从数据库中进行查询并从中创建测试。您必须在套件启动之前执行查询。不过,这种做事方式也有一些优势。您可以使用--grep 选项仅选择一部分测试,而 Mocha 将毫无问题地做到这一点。您也可以使用it.only 轻松选择单个测试。最后我检查了一下,tape 和它的兄弟姐妹在这方面遇到了麻烦。

    因此,您的 Mocha 代码无法正常工作的原因是因为您正在创建测试 Mocha 已开始运行测试。 Mocha 不会立即崩溃但是当你这样做时,你得到的行为是不确定的。我见过 Mocha 会忽略新测试的情况,也见过它以意想不到的顺序执行它的情况。

    如果这是我的测试,我会做的是:

    1. foo 中删除对it 的调用。

    2. 修改foo 以简单记录控制器实例上我关心的请求参数。

      foo(request, response) {
        // Remember to initialize this.requests in the constructor...
        this.requests.push(request);
        response.send()
      }
      
    3. 让测试it("should pass test #2"检查控制器上记录的请求:

      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 挂钩在测试之间重置控制器,以便隔离测试。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-06-21
      • 2014-08-06
      • 1970-01-01
      • 2021-05-06
      • 1970-01-01
      • 1970-01-01
      • 2015-03-24
      相关资源
      最近更新 更多