我试图为我的产品类别 updateOne prehook 方法进行单元测试。在我的模式中,为了通用保存和updateOne pre hook,我声明了以下内容。validateSaveHook()
方法,并且在那个保存预钩中,它工作得很好,我能够写一个单元测试用例。但在updateOne
前期钩子单独面临一个问题。其中,我使用了 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),
...