代码之家  ›  专栏  ›  技术社区  ›  Dave

在Jest中,我如何模拟Mongoose文档的“get”方法?

  •  0
  • Dave  · 技术社区  · 5 年前

    我使用NodeJS和MongoDB。我有一个简单的函数,用于返回文档的泛型属性。。。

    import mongoose, { Document, Schema } from "mongoose";
      
    export interface IMyObject extends Document {
    ...
    }
    
    ...
    export async function getProperty(
      req: CustomRequest<MyDto>,
      res: Response,
      next: NextFunction
    ): Promise<void> {
      const {
        params: { propertyName, code },
      } = req;
    
      try {
        const my_obj = await MyObject.findOne({ code });
        const propertyValue = my_obj ? my_obj.get(propertyName) : null;
        if (propertyValue) {
          res.status(200).json(propertyValue);
        ...
    

    我正在努力弄清楚如何测试这个功能。特别是,我如何模拟与“get”方法兼容的对象实例?我试过了

      it("Should return the proper result", async () => {
        const myObject = {
          name: "jon",
        };
    
        MyObject.findOne = jest.fn().mockResolvedValue(myObject.name);
    
        const resp = await superTestApp.get(
          "/getProperty/name/7777"
        );
        expect(resp.status).toBe(StatusCodes.OK);
        expect(resp.body).toEqual("happy");
    

    但这失败了

    TypeError: my_object.get is not a function
    
    0 回复  |  直到 5 年前
        1
  •  2
  •   AdriSolid    5 年前

    你需要 spy 你的对象及其方法。类似于:

    import MyObject from '..';
    
    const mockedData = {
      get: (v) => v
    };
    
    let objectSpy;
    
    // spy the method and set the mocked data before all tests execution
    beforeAll(() => {
      objectSpy = jest.spyOn(MyObject, 'findOne');
      objectSpy.mockReturnValue(mockedData);
    });
    
    // clear the mock the method after all tests execution
    afterAll(() => {
      objectSpy.mockClear();
    });
    
    // call your method, should be returning same content as `mockedData` const
    test('init', () => {
      const response = MyObject.findOne();
      expect(response.get('whatever')).toEqual(mockedData.get('whatever'));
    });