Мокко дает мне сообщение об ошибке после добавления проверки ввода с JOI - PullRequest
0 голосов
/ 14 июня 2019

У меня есть функциональная конечная точка API, но каждый раз, когда я добавляю логику проверки, тесты заканчиваются неудачей.

Я пытался поиграться с блоками if else, но проверки после этого, похоже, не работают (тесты в этом случае проходят).Что я здесь не так делаю?

Это мои модели данных

class User {
    constructor() {
        this.users = [];
    }

    create(data) {
        const newUser = {
            id: this.users.length + 1,
            firstName: data.firstName || '',
            lastName: data.lastName || '',
            email: data.email || '',
            password: data.password || '',
            address: data.address || '',
            isAdmin: true
        };
        this.users.push(newUser);
        return newUser;
    }
}
export default new User();

Это мой контроллер

import Joi from '@hapi/joi';
import User from '../models/user';
import schema from '../helpers/validations';

const RegisterUser = {
    create(req, res) {
        const result = Joi.validate(req.body, schema);

        if (result.error) {
            return res.status(400).json({
                status: 400,
                error: result.error.details[0].message
            });
        }

        const user = User.create(req.body);
        return res.status(201).json({
            status: 201,
            Data: user
        });
    }
};

export default RegisterUser;

Наконец-то мои тесты


chai.use(chaihttp);
chai.use(asserttype);
describe('User registration', () => {
    const user = {
        Data: {
            id: 1,
            firstName: 'John',
            email: 'johndoe@gmail.com',
            lastName: 'Doe',
            password: 'johndoe@123',
            address: '80100122',
            isAdmin: true
        }
    };
    it('should create a user', () => {
        chai.request(app)
            .post('/api/v1/auth/signup')
            .send(user)
            .end((err, res) => {
                expect(res.body)
                    .to.have.status(201)
                    .and.to.be.an('object');
                expect(res.body.Data).to.have.a.property('id');
                expect(res.body.Data)
                    .to.have.a.property('firstName')
                    .and.to.be.a('string');
                expect(res.body.Data)
                    .to.have.a.property('lastName')
                    .and.to.be.a('string');
                expect(res.body.Data)
                    .to.have.a.property('email')
                    .and.to.be.a('string');
                expect(res.body.Data)
                    .to.have.a.property('address')
                    .and.to.be.a('string');
                expect(res.body.Data)
                    .to.have.a.property('isAdmin')
                    .and.to.be.boolean();
            });
    });
});

Мои тесты не пройдены, ноконечная точка хорошо работает, когда на почтальоне.Тесты - единственные, которые провалились.Это ошибка, которую я получаю

 User registration
    ✓ should create a user
    1) should create a user

  1 passing (724ms)
  1 failing

  1) User registration
       should create a user:

      Uncaught AssertionError: expected { Object (status, error) } to have status code 201 but got 400
      + expected - actual

      -400
      +201

Это происходит, когда я меняю код состояния в моих тестах на 400

User registration
    ✓ should create a user
    1) should create a user

  1 passing (98ms)
  1 failing

  1) User registration
       should create a user:
     Uncaught AssertionError: Target cannot be null or undefined.
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...