我正在尝试为我的产品类别updateOne预钩方法介绍单元测试用例。在用于概括save和updateOne预钩子的架构中,我声明了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);
};
}
答案 0 :(得分:1)
validateSaveHook
期望上下文具有getUpdate
方法。如果上下文被嘲笑,则应提供以下方法:
const productCategory = {
product_category_has_sub_category: ...,
product_category_children: ...
};
const context = {
getUpdate: jest.fn().mockReturnValue(productCategory),
...