更新中的错误猫鼬中的一个预钩单元测试用例



我正在尝试涵盖我的产品类别更新一个预钩方法的单元测试用例。在我的泛化保存和更新的模式中一个预钩子我声明了validateSaveHook()方法,在该保存预钩子中它工作正常,我能够编写一个单元测试用例。但是在updateOne预钩子单独面临一个问题。在这种情况下,我使用getupdate()从代码中的猫鼬查询中获取值,它工作正常。在终端中编写单元测试用例时,它会抛出类似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),
...

最新更新