AssertionError: ожидается, что неопределенное значение будет равно 201 - PullRequest
0 голосов
/ 05 апреля 2019

У меня есть почтовый пользовательский API (база данных Postgres), он хорошо работает на почтальоне без ошибок, у меня bodyparser в моем app.js, .type('json'), но мой тест возвращается AssertionError: expected undefined to equal 20 1, я утешаю .log (res), который не определен. Вот мой код, мой API идет первым, а тест с mocha и chai - последним.

exports.post_user = (req, res) => {
    const {error} = validateUser(req.body);
    if (error) return res.status(422).json({ message: error.details[0].message });
    if (!req.file) return res.send('Please upload a file');
    bcrypt.hash(req.body.password, 10, async (err, hash) => {
        if (err) {
            res.status(500).json({
                message: 'retype password',
                error: err
            });
        } else {
            const text = `INSERT INTO 
    users(id, firstName, lastName, otherName, email, phoneNumber, userName, isAdmin, password, userImage, createdOn) 
    VALUES($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11) 
    returning *`;
            const values = [
                uuidv4(),
                req.body.firstName,
                req.body.lastName,
                req.body.otherName,
                req.body.email,
                req.body.phoneNumber,
                req.body.userName,
                req.body.isAdmin,
                hash,
                req.file.path,
                moment(new Date())
            ];
            try {
                const { rows } = await db.query(text, values);
                const token = jwt.sign({
                    email: rows[0].email,
                    userId: rows[0].id
                }, process.env.SECRET,
                {
                    expiresIn: '24h'
                });
                return res.status(201).json({
                    message: 'user created successfully',
                    users: rows[0],
                    token: token,
                    request: {
                        type: 'GET',
                        url: 'http://localhost:3000/api/v1/user/' + rows[0].id
                    }
                });
            } catch (err) {
                return res.status(400).json({
                    message: 'an error occur',
                    error: console.error(err)
                });
            }
        }
    });


};
process.env.NODE_ENV === 'test';

import chai from 'chai';
import chaiHttp from 'chai-http';
import app from '../../app';
import faker from 'faker';
import moment from 'moment';

const { expect } = chai;
// using chai-http middleware
chai.use(chaiHttp);

describe('POST USER', () => {
    it('Should successfully create a user account if inputs are valid', (done) => {
        chai.request(app)
            .post('/api/v1/user/signup')
            .type('json')
            .send({
                userImage: faker.image.people(),
                firstName: 'Kazeem',
                lastName: 'Odutola',
                otherName: 'Oluwatobi',
                email: 'tester@gmail.com',
                password: 'Kazeem27',
                userName: 'Kaz',
                phoneNumber: '080874568356',
                isAdmin: 'yes',
                createdOn: moment(new Date())
            })
            .then((res) => {
                // eslint-disable-next-line no-console
                console.log(res.body.data);
                const { body } = res;
                expect(body).to.be.an('object');
                expect(body.status).to.be.equals(201);
                expect(body.data).to.be.an('object');
                expect(body.data.token).to.be.a('string');
                done();
            })
            .catch((error) => done(error));
    });
});

1 Ответ

0 голосов
/ 05 апреля 2019

Строка expect (body.status).to.be.equals(201) неверна из того, что возвращает ваш контроллер. Ваше тело ответа не имеет статуса. Попробуйте res.should.have.status(201) или expect (res.status).to.equal(201)

...