Reputation: 23
For some reason when I set my app in test.js
like this:
const app = express();
I get a 404 error for all tests.
However, when I set it like this
const app = 'http://localhost:3000'
all tests pass.
I'm aware though that this is not the best way to declare app
in a testing environment. how can I avoid using a fix path like localhost ?
example:
const express = require('express');
const app = express();
// const app = 'http://localhost:3000'
const chai = require("chai");
const expect = chai.expect;
const request = require('supertest');
it('For all bookings', function (done) {
request(app)
.get('/bookings')
.end(function (err, res) {
expect('Content-Type', /json/)
expect(res.statusCode).to.be.equal(200);
done();
});
});
that way I get Uncaught AssertionError: expected 404 to equal 200
but if I uncomment const app = 'http://localhost:3000'
to use it instead of const app = express();
then the test passes.
Upvotes: 2
Views: 626
Reputation: 8443
if we did this in the test file
const app = express();
it means that we create brand new express application with no routes defined. The correct way is to use same express application not create a new one.
In order to do that, we can export the express app and refer it from the test file.
// index.js
const express = require('express')
const app = express()
const port = 3000
app.get('/bookings', (req, res) => res.send('Hello World!'))
app.listen(port, () => console.log(`Example app listening on port ${port}!`))
module.exports = app; // export express app
Meanwhile for test file
// test.js
...
const app = require("./index"); // import the app
it("For all bookings", function(done) {
request(app)
.get("/bookings")
.end(function(err, res) {
console.log(res);
expect("Content-Type", /json/);
expect(res.statusCode).to.be.equal(200);
done();
});
});
Hope it helps
Upvotes: 1
Reputation: 223259
const app = express()
creates dummy Express instance with no routes. It cannot respond to a request to /bookings
endpoint because there's no such endpoint.
That http://localhost:3000
works means that an application that has has /bookings
route is currently running.
In case application instance is provided to Supertest's request
, an instance of the application that has /bookings
route should be imported:
const app = require('./app');
Upvotes: 1