Search code examples
mongoosejestjsmongoose-schema

Error in updateOne pre hook unit test case in mongoose


I'm trying to cover the unit test case for my product category updateOne prehook method. In my schema for generalizing save and updateOne pre hook i declared validateSaveHook() methods and in that save prehook it work fine and i am able to write a unit test case. But inupdateOne pre hook alone facing an issue. In that, i used getupdate() to get the value from mongoose query in code it works fine. While writing the Unit test case in terminal it throws error like TypeError: this.getUpdate is not a function. Can anyone please tell me what wrong in my test case code and how to overcome it?

Test case

 it('should throw error when sub_category false and children is passed.', async () => {
      // Preparing
  const next = jest.fn();
      const context = {
        op: 'updateOne',
        _update: {
          product_category_has_sub_category: false,
        },
      };
      // Executing
        await validateSaveHook.call(context, next);
        expect(next).toHaveBeenCalled();
    });

schama.ts:

    export async function validateSaveHook(this: any, next: NextFunction) {
      let productCategory = this as ProductCategoryType;
      if (this.op == 'updateOne') {
        productCategory = this.getUpdate() as ProductCategoryType;
               if (!productCategory.product_category_has_sub_category && !productCategory['product_category_children']) {
          productCategory.product_category_children = [];
        }
      }
      if (productCategory.product_category_has_sub_category && isEmpty(productCategory.product_category_children)) {
        throwError("'product_category_children' is required.", 400);
      }
      if (!productCategory.product_category_has_sub_category && !isEmpty(productCategory.product_category_children)) {
        throwError("'product_category_children' should be empty.", 400);
      }
      next();
    }
export class ProductCategorySchema extends AbstractSchema {
  entityName = 'product_category';
  schemaDefinition = {
    product_category_has_sub_category: {
      type: Boolean,
      required: [true, 'product_category_has_sub_category is required.'],
    },

    product_category_children: {
      type: [Schema.Types.Mixed],
    },
  };

  indexes = ['product_category_name'];

  hooks = () => {
    this.schema?.pre('updateOne', validateSaveHook);
  };
}

Solution

  • validateSaveHook expects a context to have getUpdate method. In case a context is mocked, it should provide this method:

    const productCategory = {
      product_category_has_sub_category: ...,
      product_category_children: ...
    };
    
    const context = {
      getUpdate: jest.fn().mockReturnValue(productCategory),
      ...