0

I want to test my Express app. I do some async setup stuff before app is ready and promise resolves. So I put the tests inside the then function but they are not run.

Mocha gives no errors, instead it reports "0 tests passing". When I run the app normally (node server.js) everything works fine.

How can I run tests inside then function?

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!
});
olefrank
  • 6,452
  • 14
  • 65
  • 90
  • 1
    The problem is that you are building your test suite asynchronously. In such case, as explained in [the other question](https://stackoverflow.com/questions/38268435/how-can-i-build-my-test-suite-asynchronously) you have to use the `--delay` and call `run`. – Louis Jul 24 '17 at 10:37

1 Answers1

0

You want to use the before hook, and restructure your tests slightly. The following code should work (but I'm not typing this at a computer that has mocha set up so I can't test it).

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
    });
});
Dr_Derp
  • 1,185
  • 6
  • 17