异步等待单元测试问题

时间:2017-03-13 07:07:43

标签: javascript node.js unit-testing ecmascript-6 async-await

这是我想在模拟数据库中测试的update函数

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;

这是我为它写的测试脚本

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');
        });
    });

});

我收到此错误

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

当我检查模拟数据库时,它会更新数据,但为什么它的断言会失败?它应该在完成await调用

后更新

1 个答案:

答案 0 :(得分:2)

findOneAndUpdate方法将options作为第三个参数。其中一个选项是returnNewDocument: <boolean>。默认情况下为false。如果未将此选项设置为true,则MongoDB会更新文档并返回旧文档。如果将此选项设置为true,则MongoDB将返回新的更新文档。

来自官方文档 -

  

返回原始文档,如果是returnNewDocument:true,则返回更新的文档。

因此,在您的更新方法中,进行以下更改 -

return await Book.findOneAndUpdate({ _id: id }, { $set: data }, { returnNewDocument : true });

您可以阅读here

修改 - 如果使用mongoose,请使用{new: true}选项代替上述选项,因为mongoose使用findAndModify下面的findOneAndUpdate 1}}方法。