nogabemist
nogabemist

Reputation: 487

Chai testing TypeError: Converting circular structure to JSON

I'm a new learner express.js I want to test simple post and get operations with tdd mechanism. I created the test, route, index and db files but when I try to test POST method it gives me this error.

enter image description here

This is my routes/task.js

const express = require('express');
const router = express.Router();

router.post("/api/task", async (req,res) => {
    try {
        const task = await new Task(req.body).save();
        res.send(task);
    } catch (error) {
        res.send(error);
    }
})

This is my test/task.js

let chai = require("chai");
const chaiHttp = require("chai-http");
const { send } = require("process");
let server = require("../index");

//Assertion Style
chai.should();

chai.use(chaiHttp);

describe('Tasks API', () => {

        
    /** 
     * Test the POST Route
     */
     describe('POST /api/task', () => {
        it("It should POST a new task", () => {
            const task =  {task: "Wake Up"};
            chai.request(server)
                .post("/api/task")
                .send(task)
                .end((err, response) => {
                    response.should.have.status(201);
                    response.body.should.be.a('string');
                    response.body.should.have.property('id');
                    response.body.should.have.property('task');
                    response.body.should.have.property('task').eq("Wake Up");
                    response.body.length.should.be.eq(1);
                done();
                });
        });
    });
});

This is my db.js

var sqlite3 = require('sqlite3').verbose()

const DBSOURCE = "db.sqlite"

let db = new sqlite3.Database(DBSOURCE, (err) => {
    if (err) {
      // Cannot open database
      console.error(err.message)
      throw err
    }else{
        console.log('Connected to the SQLite database.')
        db.run(`CREATE TABLE IF NOT EXISTS todo (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            task text
            )`,
        (err) => {
            if (err) {
                // Table already created
                console.log(err);
            }
        });  
    }
});


module.exports = db

And this is my index.js

const connection = require('./db');
const express = require('express');
const app = express();
const cors = require("cors"); 


const port = process.env.PORT || 8080;

app.use(express.json());
app.use(cors());



app.get('/', (req, res) => {
    res.send('Hello World');

});

app.post('/api/task', (req, res) => {

    res.status(201).send(req);

});




app.listen(port, () => console.log(`Listening on port ${port}...`)); 

module.exports = app;

The thing that I try to do is building a test case to test the post method. I think I couldn't built the correct relations the files.

Upvotes: 3

Views: 425

Answers (1)

Ionică Bizău
Ionică Bizău

Reputation: 113465

Currently, just by doing a POST request to /api/task, the error will appear. That is because of these lines in index.js:

app.post('/api/task', (req, res) => {
    res.status(201).send(req);
});

The req parameter is circular, hence cannot be JSON-stringified.

Solution

In routes/task.js export the router:

const express = require('express');
const router = express.Router();

router.post("/api/task", async (req,res) => {
    try {
        const task = await new Task(req.body).save();
        res.send(task);
    } catch (error) {
        res.send(error);
    }
})

// By adding this line you can export the router
module.exports = router

In index.js, include the routes/task.js file and pass it to app.use(...), also remove the now-obsolete /api/task route:

const connection = require('./db');
const express = require('express');
const app = express();
const cors = require("cors");
const taskRoutes = require("./routes/task")


const port = process.env.PORT || 8080;

app.use(express.json());
app.use(cors());

app.get('/', (req, res) => {
    res.send('Hello World');
});

app.use(taskRoutes)

app.listen(port, () => console.log(`Listening on port ${port}...`));

module.exports = app;

This way we got rid of the circular structure stringifying and the tests should now pass.

Upvotes: 1

Related Questions