猫鼬中updateOne预挂钩单元测试用例出错

Error in updateOne pre hook unit test case in mongoose

我正在尝试涵盖我的产品类别 updateOne prehook 方法的单元测试用例。在我用于概括 save 和 updateOne pre hook 的模式中,我声明了 validateSaveHook() 方法,并且在那个 save prehook 中它工作正常,我能够编写一个单元测试用例。但是在updateOne pre hook 单独面临一个问题。在那里,我使用 getupdate() 在代码中从 mongoose 查询中获取值,它工作正常。在终端中编写单元测试用例时会抛出 TypeError: this.getUpdate is not a function 之类的错误。谁能告诉我我的测试用例代码有什么问题以及如何克服它?

测试用例

 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);
  };
}

validateSaveHook 期望上下文具有 getUpdate 方法。如果上下文被模拟,它应该提供这个方法:

const productCategory = {
  product_category_has_sub_category: ...,
  product_category_children: ...
};

const context = {
  getUpdate: jest.fn().mockReturnValue(productCategory),
  ...