【问题标题】:Async await unit testing issue异步等待单元测试问题
【发布时间】:2017-03-13 07:07:43
【问题描述】:

这是我想在模拟数据库中测试的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调用后应该已经更新了

【问题讨论】:

  • console.log(result) 给你什么?
  • @lonesomeday 和book一模一样,好像还没更新一样

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


【解决方案1】:

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} 选项而不是上述选项,因为mongoosefindOneAndUpdate 方法下方使用findAndModify

【讨论】:

  • 非常感谢。只是对你的回答稍作修改,正确的选项是:{ new: true}
  • @necroface 我想你正在使用mongoose。我提供的文档是针对本机 MongoDB 驱动程序的 :) 我会在答案中提到这一点。
猜你喜欢
  • 1970-01-01
  • 2017-06-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-11
  • 1970-01-01
  • 1970-01-01
  • 2018-12-09
  • 2018-01-29
相关资源
最近更新 更多