简体   繁体   中英

Testing on Nodejs with supertest gives “Cannot read property 'header' of undefined” error

I've server.js file and It has my express app. For test usage, I could run a demo test with using express in test file like below, but I can't run my test succesfuly :(

const request = require('supertest');
const express = require('express');

const app = express();

app.get('/user', function(req, res) {
  res.status(200).json({ name: 'tobi' });
});

request(app)
  .get('/user')
  .expect('Content-Type', /json/)
  .expect('Content-Length', '15')
  .expect(200)
  .end(function(err, res) {
    if (err) throw err;
  });

  describe('GET /user', function() {
    it('respond with json', function(done) {
      request(app)
        .get('/user')
        .set('Accept', 'application/json')
        .expect('Content-Type', /json/)
        .expect(200, done);
    });
  });

But if I try to use my app which is in server like below:

const server = ('../server');
const request = require("supertest")

describe("Upload Page Test", (done) => {
    describe("(GET /alive) returns webpage ", (done) => {
        it("Is service alive", done => {
            request(server)
                .get("/alive")
                .set('Accept', 'text/html; charset=utf-8')
                .expect('Content-Type', 'text/html; charset=utf-8')
                .expect('Content-Length', '2')
                .end((err, res) => {
                    if (err) console.log("Error "+err);
                    console.log(JSON.stringify(res));
                    done();
                });
        });
    });
});

And I get an error

superagent GET ../server/alive +0ms
Error TypeError: Cannot read property 'header' of undefined
undefined

My server file's implementation is like;

const app = express();
...
...
app.get("/alive", (req, res) => {
  console.log('alive service is running');
  var promise = Provider.find({});
  promise
    .then(providers => {
      console.log('alive service is OK');
      res.send("OK");
    })
    .catch(err => {
      console.log('alive service is FAILED');
      res.send("ERROR");
    });
});

...
...
module.exports = app;

FIXED. I didn't write reqiure for server.. :)

FIXED. reqiure() is not there for server...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM