如何在Jest中模拟Mongoose的'find()'函数?

时间:2019-11-04 15:00:00

标签: javascript node.js mongodb mongoose jestjs

我有服务

export default class WorldService {

constructor(worldModel) {
    this.worldModel = worldModel;
  }

  async getWorlds() {
    let resData = {};
    await this.worldModel.find({}, (err, worlds) => {
      resData = worlds;
    });
    return resData;
  }
}

我有一个猫鼬模型

import mongoose from 'mongoose';

const worldSchema = mongoose.Schema({
  name: {
    type: String,
    required: true,
  },
});

export default mongoose.model('World', worldSchema);

我想模拟Mongoose模型并测试名为getWorlds()的服务功能。我在项目中使用 Jest 作为测试框架。

我试图用Jest编写单元测试

import WorldModel from '../../../src/models/world';
import WorldService from '../../../src/services/world';

describe('When data is valid', () => {
  beforeAll(() => {
    jest.spyOn(WorldModel, 'find').mockReturnValue(Promise.resolve([
      { _id: '5dbff32e367a343830cd2f49', name: 'Earth', __v: 0 },
      { _id: '5dbff89209dee20b18091ec3', name: 'Mars', __v: 0 },
    ]));
  });

  it('Should return entries', async () => {
    const worldService = new WorldService(WorldModel);

    const expected = [
      { _id: '5dbff32e367a343830cd2f49', name: 'Earth', __v: 0 },
      { _id: '5dbff89209dee20b18091ec3', name: 'Mars', __v: 0 },
    ];
    await expect(worldService.getWorlds()).resolves.toEqual(expected);
  });
});

我得到一个失败的答案:

 FAIL  test/unit/services/world.test.js
  When data is valid
    × Should return entries (9ms)

  ● When data is valid › Should return entries

    expect(received).resolves.toEqual(expected) // deep equality

    Expected: [{"__v": 0, "_id": "5dbff32e367a343830cd2f49", "name": "Earth"}, {"__v": 0, "_id": "5dbff89209dee20b18091ec3", "name": "Mars"}]
    Received: {}

如何在Jest中模拟猫鼬 find()函数?

P.s。我不想对 MongoDB 使用任何更高级别的测试框架,例如 mockgoose

1 个答案:

答案 0 :(得分:1)

您的服务有问题,如果您使用async await,则无需进行回调:

export default class WorldService {
    constructor (worldModel) {
        this.worldModel = worldModel;
    }

    async getWorlds () {
        let resData = {};

        try {
            resData = await this.worldModel.find({});
        } catch (e) {
            console.log('Error occured in getWorlds', e);
        }

        return resData;
    }
}

我用它来模拟mongoose模型的find方法:

describe('When data is valid', () => {
    beforeAll(() => {
        WorldModel.find = jest.fn().mockResolvedValue([{
                _id: '5dbff32e367a343830cd2f49',
                name: 'Earth',
                __v: 0
            },
            {
                _id: '5dbff89209dee20b18091ec3',
                name: 'Mars',
                __v: 0
            },
        ])
    });

    it('Should return entries', async () => {
        const worldService = new WorldService(WorldModel);

        const expected = [{
                _id: '5dbff32e367a343830cd2f49',
                name: 'Earth',
                __v: 0
            },
            {
                _id: '5dbff89209dee20b18091ec3',
                name: 'Mars',
                __v: 0
            },
        ];
        await expect(worldService.getWorlds()).resolves.toEqual(expected);
    });
});