gpt4 book ai didi

node.js - Mocha 忽略了一些测试,尽管它们应该运行

转载 作者:太空宇宙 更新时间:2023-11-03 23:24:29 26 4
gpt4 key购买 nike

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

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

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那里的一些东西,它出现在Mocha日志中我期望它出现的地方。

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

最佳答案

看起来您正在从 tape 或类似的测试运行程序迁移到 Mocha。您将需要显着改变您的方法,因为 Mocha 的工作方式显着不同。

tape 和类似的运行程序不需要提前知道套件中存在哪些测试。他们在执行测试代码时发现测试,并且一个测试可以包含另一个测试。另一方面,Mocha 要求在运行任何测试之前可以发现整个套件。*它需要了解套件中存在的每个测试。它有一些缺点,因为您无法在 Mocha 运行测试时添加测试。例如,您不能使用 before Hook 从数据库进行查询并从中创建测试。您必须在套件启动之前执行查询。然而,这种做事方式也有一些优点。您可以使用 --grep 选项仅选择测试的子集,Mocha 会毫无问题地执行此操作。您还可以使用 it.only 轻松选择单个测试。上次我检查过,tape 及其同级产品在执行此操作时遇到了困难。

因此,您的 Mocha 代码无法正常工作的原因是您在 Mocha 开始运行测试之后创建了一个测试。Mocha 不会立即崩溃,但当您执行此操作时,您得到的行为是未定义的。我见过 Mocha 会忽略新测试的情况,也见过它以意外顺序执行的情况。

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

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

  2. 修改 foo 以简单地在 Controller 实例上记录我关心的请求参数。

    foo(request, response) {
    // Remember to initialize this.requests in the constructor...
    this.requests.push(request);
    response.send()
    }
  3. 让测试 it("should pass test #2" 检查 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)
    expect(controler.requests).to.have.lengthOf(1);
    // etc...
    done()
    })
    })
  4. 并且会使用 beforeEach Hook 在测试之间重置 Controller ,以便隔离测试。

关于node.js - Mocha 忽略了一些测试,尽管它们应该运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45987387/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com