【问题标题】:How to fix toArray is not undefined in Jest如何修复 toArray 在 Jest 中未定义
【发布时间】:2019-09-27 11:06:43
【问题描述】:

我正在使用 Jest 创建一个单元测试并运行测试我得到一个测试错误:“TypeError: db.find(...).toArray is not a function”。如果有人可以帮助我,我将不胜感激。

问候 :)

'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 is not a function”

【问题讨论】:

    标签: javascript mongodb jestjs


    【解决方案1】:

    好吧,你没有告诉我们db 来自哪里,但我猜db.find(...) 不会返回结果集。

    将您的代码更改为:

    var dbResult = db.find(...)
    expect(dbResult.toArray).toBeDefined
    

    这将允许您断言您有一个定义了 toArray 方法的对象。

    可能有更好的方法来断言,但你没有包含足够的代码来解决这个问题,所以我猜。

    【讨论】:

    • 控制器中的find方法为:pastebin.com/QVGSp2YPexports.find = async ctx => { db = MongoClient.getDb(); await db.find({}, { '_id': 0 }).toArray() .then((result) => { let msj = dto.transform(result, 'array'); return ctx.res.ok( { 数据: msj }); }) .catch(e => { console.log(e); }); };
    猜你喜欢
    • 2019-05-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-16
    • 2019-09-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多