Search code examples
node.jsunit-testingtddsupertest

node module supertest - post method not working


I have this test below to test a controller /post endpoint but when I run this test, it keeps complaining about missing fields. I am providing the correct data in .send() method but for some reason its not able to detect it and says that the name field is missing.

    describe("/POST a book", () => {
        it("should save a book", async () => {
            var book_data = { name: "book_title" };
            const res = await request(app).post("/books")
            .send(book_data)
            .expect(201)
            .end(function(err, res) {
              if (err) return done(err);
              done();
            });
        });
    });

routes.js

 app.post('/books', [bookController.create_a_book]);

bookController.js

exports.create_a_book = function (req, res) {
    BookModel.createBook(req.body).then(
        (book) => {
            res.status(200).send({id: book._id});
        }
    );
};

Any idea what I am doing wrong here? I didnt see anything different from the online posts about it.


Solution

  • Here is an integration test for your case, maybe you forget add the body-parser middleware.

    server.js:

    const express = require("express");
    const bookController = require("./bookController");
    const http = require("http");
    const bodyParser = require("body-parser");
    
    const app = express();
    
    app.use(bodyParser.json());
    app.post("/books", [bookController.create_a_book]);
    
    const server = http.createServer(app).listen(3000, () => {
      console.log("HTTP server is listening on http://localhost:3000");
    });
    
    module.exports = server;
    

    bookController.js:

    const BookModel = require("./bookModel");
    
    exports.create_a_book = function(req, res) {
      BookModel.createBook(req.body).then((book) => {
        console.log("book: ", book);
        res.status(200).send({ id: book._id });
      });
    };
    

    bookModel.js:

    module.exports = {
      async createBook(data) {
        data._id = Math.random();
        return data;
      },
    };
    

    server.integration.spec.js:

    const request = require("supertest");
    const { expect } = require("chai");
    const app = require("./server");
    
    describe("/POST a book", () => {
      after((done) => {
        app.close(done);
      });
      it("should save a book", (done) => {
        const book_data = { name: "book_title" };
        request(app)
          .post("/books")
          .send(book_data)
          .expect(200)
          .end(function(err, res) {
            console.log(res.body);
            if (err) return done(err);
            expect(res.body).to.haveOwnProperty("id");
            done();
          });
      });
    });
    

    Integration test result with coverage report:

    HTTP server is listening on http://localhost:3000
      /POST a book
    book:  { name: 'book_title', _id: 0.2510749824531193 }
    { id: 0.2510749824531193 }
        ✓ should save a book (497ms)
    
    
      1 passing (502ms)
    
    ----------------------------|----------|----------|----------|----------|-------------------|
    File                        |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
    ----------------------------|----------|----------|----------|----------|-------------------|
    All files                   |    96.88 |       50 |      100 |      100 |                   |
     bookController.js          |      100 |      100 |      100 |      100 |                   |
     bookModel.js               |      100 |      100 |      100 |      100 |                   |
     server.integration.spec.js |    92.86 |       50 |      100 |      100 |                18 |
     server.js                  |      100 |      100 |      100 |      100 |                   |
    ----------------------------|----------|----------|----------|----------|-------------------|
    

    Source code: https://github.com/mrdulin/mocha-chai-sinon-codelab/tree/master/src/stackoverflow/58924579