NodeJS 使用Mocha和Chai的单元测试用例,一个Express Crud应用程序,它包含基本的凝乳操作(获取、发布、修补和删除)

arknldoa  于 2022-12-12  发布在  Node.js
关注(0)|答案(2)|浏览(77)

下面是代码和测试结果
用户. js文件

const express = require("express");
const User = require("../db/models/user");

const userRouter = new express.Router();

userRouter.post("/user", async(req, res) => {
    try {
        const user = new User(req.body);
        await user.save();
        res.status(201).send();
    } catch(e) {
        res.status(400).send(e);
    }
})

userRouter.get("/user", async(req, res) => {
    const users = await User.find();
    res.send(users);
})

userRouter.patch("/user/:id", async (req, res) => {
    const id = req.params.id;
    const updates = Object.keys(req.body);
    try {
        const user = await User.findById(id);
        updates.forEach((update) => (user[update] = req.body[update]));
        await user.save();
        res.send(user);
    } catch (e) {
        res.status(400).send({ error: e.message });
    }
});

userRouter.delete("/user/:id", async(req, res) => {
    try {
        const id = req.params.id;
        await User.deleteOne({_id: id});
        res.send();
    } catch(e) {
        res.status(400).send(e);
    }
})

module.exports = userRouter;

用户测试. js文件

const app = require("../src/app");
const User = require("../src/db/models/user");
const { userOne, userOneObjectID, setUpDataBase } = require("./utils/db");
const request = require("supertest");
const chai = require("chai");
const expect = chai.expect;
const should = chai.should();

beforeEach(setUpDataBase);

describe("TestCases", () => {
  
  it('get user', async function (done) {
    const response = await request(app).get("/user");
    //expect(response.body).to.be.an('array')
    expect(response.body.length).to.eql(1);
  });

  it('post user', async function (done) {
    const response = await request(app).post("/user").send({ firstName: 'Ankit', lastName: 'Parmar', age: 45, email: 'hello@gmail.com' });
    expect(response.statusCode).to.eql(201);
    done();
  });

  it('delete user', async function (done) {
    const response = await request(app).delete("/user/950490345934");
    expect(response.statusCode).to.eql(200);
  });

})

package.json

{
    "name": "nodejs_crud",
    "version": "1.0.0",
    "description": "",
    "main": "index.js",
    "dependencies": {
        "chai": "^4.2.0",
        "express": "^4.17.1",
        "fs": "0.0.1-security",
        "istanbul": "^0.4.5",
        "mocha-junit-reporter": "^2.0.0",
        "mongoose": "^5.9.25",
        "nyc": "^15.1.0",
        "pm2": "^4.4.0",
        "supertest": "^4.0.2",
        "xml-js": "^1.6.11"
    },
    "devDependencies": {
        "mocha": "^7.1.0"
    },
    "scripts": {
        "start": "nodemon src/index.js",
        "test": "nyc mocha --timeout 10000 --reporter mocha-junit-reporter --exit"
    },
    "nyc": {
        "exclude": [
            "**/sentryHelper.*",
            "**/*.test.*"
        ],
        "extension": [
            ".ts"
        ],
        "reporter": [
            "lcov",
            "text"
        ]
    },
    "keywords": [],
    "author": "",
    "license": "ISC"
}

这是测试失败的结果。

$ npm test

> nodejs_crud@1.0.0 test D:\Develop\nodejs\testing\hands-on
> nyc mocha --timeout 10000 --reporter mocha-junit-reporter --exit

---------------|---------|----------|---------|---------|-------------------
File           | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
---------------|---------|----------|---------|---------|-------------------
All files      |   84.05 |      100 |      80 |   85.29 |
 src           |     100 |      100 |     100 |     100 |
  app.js       |     100 |      100 |     100 |     100 |
 src/db        |     100 |      100 |     100 |     100 |
  mongoose.js  |     100 |      100 |     100 |     100 |
 src/db/models |     100 |      100 |     100 |     100 |
  user.js      |     100 |      100 |     100 |     100 |
 src/router    |   62.06 |      100 |      60 |   64.28 |
  user.js      |   62.06 |      100 |      60 |   64.28 | 12,22-30,40
 test          |     100 |      100 |     100 |     100 |
  usertest.js  |     100 |      100 |     100 |     100 |
 test/utils    |     100 |      100 |     100 |     100 |
  db.js        |     100 |      100 |     100 |     100 |
---------------|---------|----------|---------|---------|-------------------
npm ERR! Test failed.  See above for more details.

有人能帮我解决这个问题吗?
我用摩卡和柴来测试积垢操作。
我面临的问题后,删除和补丁,因为他们给予两个响应,并使用try-catch,所以我们可以如何编写测试代码?

c9qzyr3d

c9qzyr3d1#

试一下,它正在工作。用下面的代码代替描述测试函数。

describe('Crud testing', function() {
   it('get user', function() {
  request(app)
.get('/user')
.expect(200)
.end(function(err, res) {
});
  });

  it('post user', function() {
const user = new User({firstName: "Anurag",
lastName: "Singh",
age: 24,
email: "anurag@gmail.com"});
  request(app)
.post('/user')
.send(user)
.expect(201)
.end(function(err, res) {
});
  });
  it('post user  unsuccesfull', function() {
  request(app)
.post('/user')
.send()
.expect(400)
.end(function(err, res) {
});
  });
  it('patch user succesfull', function(done) {
  request(app)
.patch('/user/'+ userOneObjectID)
.send({firstName: "Anurag",
lastName: "Singh",
age: 24,
email: "anurag@gmail.com"})
.expect(Object.getOwnPropertyNames)
.end(function(err, res) {
  res.body.age.should.be.eql(24);
  done();
});
  });
  it('patch user unsuccessful', function() {
  request(app)
   .patch('/user/45')
.send(
  {lastName: "Chandel"}
)
.expect(400)
.end(function(err, res) {
});
  });
  it('delete user  succesfull', function() {
  request(app)
.delete('/user/950490345934/')
.expect(200)
.end(function(err, res) {
});
  });
  it('delete user unsuccesfull', function() {
  request(app)
.delete('/user/78752/')
.expect(400)
.end(function(err, res) {
});
  });
   
});
qmelpv7a

qmelpv7a2#

节点js_crud@1.0.0测试:nyc mocha --timeout 10000 --reporter mocha-junit-reporter --exit npm错误!退出状态1
我得到这个错误。尝试你的代码和它的工作,请告诉为什么?。我的代码覆盖率是100%。

相关问题