javascript - 异步等待单元测试问题

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

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

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 调用后,它应该已经更新了

最佳答案

findOneAndUpdate方法需要 options作为第三个参数。选项之一是 returnNewDocument: <boolean> 。这是false默认情况下。如果您不将此选项设置为 true然后 MongoDB 更新文档并返回旧文档作为结果。如果将此选项设置为 true然后 MongoDB 返回新的更新文档。

来自官方文档 -

Returns either the original document or, if returnNewDocument: true, the updated document.

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

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

您可以阅读here .

编辑 - 如果使用mongoose然后使用 {new: true}选项而不是上面的选项 mongoose使用 findAndModifyfindOneAndUpdate下方方法。

关于javascript - 异步等待单元测试问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42758117/

相关文章:

javascript - 网站如何禁止粘贴文本?

javascript - 在 php 中从 Ajax/Jquery 获取表单 $_POST 数据

javascript - 循环遍历字符串数组 - 停留在最后一个字符串

node.js - 如何将 aws-sdk 与 node.js 一起使用

javascript - 如何使用 Browserify 实现 Synchronize.js?

c# - 是否应该为事件驱动代码中的私有(private)方法编写单元测试?

ios - Grand Central Dispatch 和单元测试

c# - 如何在 NUnit 中编写集成测试?

javascript - 在构建和部署时使用 Angularjs 模板缓存

node.js - 快速 mongo session 存储