Monday 13 March 2017

Async await unit testing issue

This is the update function I want to test in mocked database

import Book from '../model/book';

function bookRepository(db) {
    this.db = db;
};

bookRepository.prototype.update = async function(id, data) {
    return await Book.findOneAndUpdate({ _id: id }, { $set: data });
}

export default bookRepository;

This is test script I wrote for it

import chai from 'chai';
import chaiAsPromised from 'chai-as-promised';
chai.use(chaiAsPromised);
const expect = chai.expect;

import app from '../../server';
import bookRepo from '../../repository/book';
const Book = new bookRepo(app.db);

describe('Test repository: book', () => {

    describe('update', () => {
        let id;
        beforeEach(async() => {
            let book = {
                name: 'Records of the Three Kingdoms',
                type: 'novel',
                description: 'History of the late Eastern Han dynasty (c. 184–220 AD) and the Three Kingdoms period (220–280 AD)',
                author: 'Luo Guanzhong',
                language: 'Chinese'
            };
            let result = await Book.insert(book);
            id = await result.id;
            return;
        });
        it('Update successfully', async() => {
            let data = {
                type: 'history',
                author: 'Chen Shou'
            };
            let result = await Book.update(id, data);
            await expect(result).to.be.an('object');
            await expect(result.type).to.be.equal('history');
            return expect(result.author).to.be.equal('Chen Shou');
        });
    });

});

And I received this error

AssertionError: expected 'novel' to equal 'history'
      + expected - actual

When I check the mocked database, it does update data, but why does its assertion fail? It should have already updated after completing await call



via necroface

No comments:

Post a Comment