0

我有一条路线,我正在这条路线上进行摩卡测试。测试失败并显示错误消息 Uncaught AssertionError: expected undefined to equal 201'

我已经检查了测试用例,一切似乎都很好。任何知道可能出了什么问题的人

测试

import chai from 'chai';
import chaiHttp from 'chai-http';
import app from '../src/app';
import vehicles from '../src/db/carDb';

const { expect } = chai;
chai.use(chaiHttp);

describe('Car', () => {
  it('should create new car in app', (done) => {
    const car = {
      state: 'used',
      status: 'available',
      price: 2000000,
      manufacturer: 'toyota',
      model: 'camry',
      bodyType: 'car',
    };
    chai.request(app)
      .post('/api/v1/car')
      .send(car)
      .end((err, res) => {
        const { body } = res;
        if (err) done(err);
        expect(res).to.be.an('object');
        expect(body.status).to.equal(201);
        expect(res.body.message).to.be.equal('Vehicle created successfully');
        done();
      });
  });
});

控制器

static createCar(req, res) {
    const { errors, isValid } = validateNewCar(req.body);
    if (!isValid) {
      return res.status(400).json({ errors });
    }
    const vehicle = {
      id: vehicles.length + 1,
      userId: 3,
      state: req.body.state,
      status: 'available',
      price: req.body.price,
      manufacturer: req.body.manufacturer,
      model: req.body.model,
      bodyType: req.body.bodyType
    };

    vehicles.push(vehicle);
    return res.status(201).json({
      status: 201,
      message: 'Vehicle created successfully',
      data: vehicle,
    });
  }

我希望测试通过,但应用返回 undefined

4

1 回答 1

0
expect(body.status).to.equal(201);

你的错误说body.statusundefined.

如果您查看chai-http文档并查找status,您会发现它们使用了专门设计的语法:

expect(res).to.have.status(201);

但是,您可能(没有测试过)将状态代码作为标准 http.ServerResponse实例,它不会在正文中,而是:

expect(res.statusCode).to.equal(201);
于 2019-06-13T08:24:17.740 回答