【问题标题】:mocha run tests when promise is resolved [duplicate]承诺解决时 mocha 运行测试 [重复]
【发布时间】:2017-12-29 06:32:43
【问题描述】:

我想测试我的 Express 应用。在应用程序准备好并承诺解决之前,我做了一些异步设置。所以我将测试放在then 函数中,但它们没有运行。

Mocha 没有给出任何错误,而是报告“0 个测试通过”。当我正常运行应用程序(节点 server.js)时,一切正常。

如何在 then 函数中运行测试?

const app = new App();

app.ready.then(() => {
    const express = app.express;

    describe("GET api/v1/posts", test( () => {

        beforeEach((done) => {
            instance.testHelper();
            done();
        });

        it("responds with array of 2 json objects", () => {
            return chai.request(express).get("/api/v1/posts")
                .then((res: ChaiHttp.Response) => {
                    expect(res.status).to.equal(200);
                    expect(res).to.be.json;
                    expect(res.body).to.be.an("array");
                    expect(res.body.length).to.equal(2);
                });
        });

        it("json objects has correct shape", () => {
            return chai.request(express)
                .get("/api/v1/posts")
                .then((res: ChaiHttp.Response) => {
                    const all: Post[] = res.body as Post[];
                    const post: Post = all[0];

                    expect( post ).to.have.all.keys( ["id", "author", "text"] );
                });
        });
    }));
})
.catch( (err) => {
    console.err(err);  // no errors!
});

【问题讨论】:

  • 问题是您正在异步构建测试套件。在这种情况下,如the other question 中所述,您必须使用--delay 并调用run

标签: javascript node.js asynchronous mocha.js


【解决方案1】:

您想使用before 挂钩,并稍微重组您的测试。 下面的代码应该可以工作(但我不是在安装了 mocha 的计算机上输入的,所以我无法对其进行测试)。

const app = new App();
describe('the test to run', () => {
    let express = null;
    before((done) => {
        app.ready.then(() => {
            express = app.express;
            done();
        });
    });

    it("test here", () => {
        // some test
    });
});

【讨论】:

  • 不起作用。使用 --delay 代替评论中建议的广告
  • 好吧,只要这对你有用 :)
猜你喜欢
  • 1970-01-01
  • 2017-07-22
  • 1970-01-01
  • 2015-04-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-26
  • 2020-10-21
相关资源
最近更新 更多