这是我想在模拟数据库中测试的更新
函数
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
使用 findAndModify
在findOneAndUpdate
下方方法。
关于javascript - 异步等待单元测试问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42758117/