node.js - Chai 测试 TypeError : Converting circular structure to JSON

标签 node.js express mocha.js chai

我是 express.js 的新手,我想用 tdd 机制测试简单的 post 和 get 操作。我创建了测试、路由、索引和数据库文件,但是当我尝试测试 POST 方法时,它给了我这个错误。

enter image description here

这是我的 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);
    }
})

这是我的测试/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();
                });
        });
    });
});

这是我的 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

这是我的 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;

我尝试做的事情是构建一个测试用例来测试 post 方法。我想我无法建立正确的文件关系。

最佳答案

目前,只要对/api/task 进行POST 请求,就会出现该错误。这是因为 index.js 中的这些行:

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

req 参数是循环的,因此不能被 JSON 字符串化。

解决方案

routes/task.js 中导出 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

index.js 中,包含 routes/task.js 文件并将其传递给 app.use(.. .),同时删除现已过时的 /api/task 路由:

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;

这样我们就摆脱了循环结构字符串化,现在测试应该通过了。

关于node.js - Chai 测试 TypeError : Converting circular structure to JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70536106/

相关文章:

javascript - 如何使用 sequelize beforeCreate 自动生成 Id 值?

javascript - 如何改进我在 nodejs 中的代码?

javascript - Grunt 运行 mocha - 测试失败时中止

unit-testing - 如何使用 Mocha 在 Angular.js 中测试使用 angular.module().controller() 创建的 Controller

sql - 过程数据库代码与多个数据库调用

javascript - 错误 : THREE. PlaneBufferGeometry 不是构造函数

javascript - RxJS 中的 self 修复错误处理

node.js - 无法基于 TutorialsPoint 上的 Node.js 教程进行 POST 和 DELETE

node.js - 如何创建nodejs服务器的多个实例

node.js - 在 npm 测试阶段使用不同的数据库