我正在用Jest创建一个单元测试,然后运行测试,但测试出现错误:“ TypeError:db.find(...)。toArray不是函数”。如果有人可以帮助我,我将不胜感激。
问候:)
'use strict';
const DB = require('../../../../app/databases/mongo');
jest.mock('../../../../app/databases/mongo');
const noteController = require('../../../../app/controllers/note');
function functionMock(returnValue) {
const find = jest.fn(() => Promise.resolve(returnValue));
return jest.fn(() => ({
find: () => ({ find })
}));
}
describe('noteController', () => {
beforeAll(() => {
DB.getDb.mockImplementation(functionMock(null));
});
describe('note controller', () => {
describe('find', () => {
it('note list', async done => {
const ctx = jest.fn();
await noteController.find(ctx)
.then(result => {
expect(result).toBeDefined();
});
done();
})
})
})
});
我期望在promise解析中输出带有数据,但是我得到:“ TypeError:db.find(...)。toArray不是一个函数”
答案 0 :(得分:0)
好吧,您没有告诉我们db
的来源,但是我猜测db.find(...)
不会返回结果集。
将代码更改为:
var dbResult = db.find(...)
expect(dbResult.toArray).toBeDefined
这将允许您断言您具有定义了toArray
方法的对象。
可能有一种更好的断言方式,但是您没有包含足够的代码来弄清楚这一点,所以我猜测。