AssertionError: ожидается, что {Object (driver, name, ...)} будет иметь свойство '_id' - PullRequest
2 голосов
/ 30 января 2020

Я новичок в модульном тестировании с использованием Mocha и Chai. Я пытаюсь реализовать модульное тестирование на REST-API, который написан с использованием Node.js и MongoDB. Я пробовал один урок, но я получаю AssertionError: expected { Object (driver, name, ...) } to have property '_id' при запуске npm test. Преимущественно он должен вводить данные в MongoDB.

приложение. js

const express = require('express');
const bodyParser = require('body-parser');
const app = express();

const Note = require('./db/models/note.js').Note;

app.use(bodyParser.json());

app.get('/notes', (req, res) => {
  Note.find()
    .then((notes) => res.status(200).send(notes))
    .catch((err) => res.status(400).send(err));
});

app.post('/notes', (req, res) => {
  const body = req.body;
  const note = new Note({
    name: body.name,
    text: body.text
  });
  note.save(note)
    .then((note) => res.status(201).send(note))
    .catch((err) => res.status(400).send(err));
});

module.exports = app;

тест. js

process.env.NODE_ENV = 'test';

const expect = require('chai').expect;
const request = require('supertest');

const app = require('../../../app.js');
const conn = require('../../../db/index.js');

describe('POST /notes', () => {
  before((done) => {
    conn.connect()
      .then(() => done())
      .catch((err) => done(err));
  })

  after((done) => {
    conn.close()
      .then(() => done())
      .catch((err) => done(err));
  })

  it('OK, creating a new note works', (done) => {
    request(app).post('/notes')
      .send({ name: 'NOTE Name', text: "AAA" })
      .then((res) => {
        const body = res.body;
        expect(body).to.contain.property('_id');
        expect(body).to.contain.property('name');
        expect(body).to.contain.property('text');
        done();
      })
      .catch((err) => done(err));
  })

  it('Fail, note requires text', (done) => {
    request(app).post('/notes')
      .send({ name: 'NOTE' })
      .then((res) => {
        const body = res.body;
        expect(body.errors.text.name)
          .to.equal('ValidatorError')
        done();
      })
      .catch((err) => done(err));
  });
})

1 Ответ

1 голос
/ 30 января 2020

res.body в тестовом запросе не содержит свойства _id. res.body в тесте может быть отлажено / зарегистрировано, чтобы узнать, как выглядит объект заметки. Обещание вообще возвращает объект? Если да, содержит ли оно свойство _id? Тест может быть изменен соответственно.

...