我有服务:

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中模拟Mongoose find()函数?

P.s.我宁愿不要对MongoDB使用任何更高级别的测试框架,例如嘲笑。

最佳答案

您的服务有问题,如果使用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);
    });
});

关于javascript - 如何在Jest中模拟Mongoose的'find()'函数?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58695989/

10-09 18:08