[英]Async await unit testing issue
This is the update
function I want to test in mocked database 这是我要在模拟数据库中测试的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;
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 完成await
呼叫后,它应该已经更新
The findOneAndUpdate
method takes options
as the third argument. findOneAndUpdate
方法将options
作为第三个参数。 One of the options is returnNewDocument: <boolean>
. 选项之一是returnNewDocument: <boolean>
。 This is false
by default. 默认情况下为false
。 If you don't set this option as true
then MongoDB updates the document and returns the old document as a result. 如果您未将此选项设置为true
则MongoDB将更新文档并返回旧文档。 If you set this option to true
then MongoDB returns the new updated document. 如果将此选项设置为true
则MongoDB返回新的更新文档。
From the official docs - 从官方文档-
Returns either the original document or, if returnNewDocument: true, the updated document. 返回原始文档,或者如果返回newDocument:true,则返回更新的文档。
So in your update method, make the following change - 因此,在您的更新方法中,进行以下更改-
return await Book.findOneAndUpdate({ _id: id }, { $set: data }, { returnNewDocument : true });
You can read about it here . 你可以在这里阅读。
Edit - If using mongoose
then use the {new: true}
option instead of the above option as mongoose
uses the findAndModify
underneath the findOneAndUpdate
method. 编辑 -如果使用mongoose
然后使用{new: true}
上面的选项的选项,而不是如mongoose
使用findAndModify
的下方findOneAndUpdate
方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.