Angular单元测试里pipe的mock设计

时间:2022-07-26
本文章向大家介绍Angular单元测试里pipe的mock设计,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

我想对下列这个Component的UI进行单元测试。其中有一个自定义的cxUrl pipe,在单元测试时,我需要对其进行Mock:

解决方法,在单元测试的实现代码里,创建一个用@Pipe修饰过的MockUrlPipe,在其transform方法里什么都不做即可:

运行时的截图: refreshView里执行视图的template函数:

templateFn:

准备展开routerLink:

/**
 * Invokes a pipe with 1 arguments.
 *
 * This instruction acts as a guard to {@link PipeTransform#transform} invoking
 * the pipe only when an input to the pipe changes.
 *
 * @param index Pipe index where the pipe was stored on creation.
 * @param slotOffset the offset in the reserved slot space
 * @param v1 1st argument to {@link PipeTransform#transform}.
 *
 * @codeGenApi
 */

只有当pipe的输入参数发生变化时,ɵɵpipeBind1才会触发:

pipeInstance.transform就是单元测试代码里的pipe mock实现:

/**
 * If the value of the provided exp has changed, calls the pure function to return
 * an updated value. Or if the value has not changed, returns cached value.
 *
 * @param lView LView in which the function is being executed.
 * @param bindingRoot Binding root index.
 * @param slotOffset the offset from binding root to the reserved slot
 * @param pureFn Function that returns an updated value
 * @param exp Updated expression value
 * @param thisArg Optional calling context of pureFn
 * @returns Updated or cached value
 */

绑定表达式的值发生变化时,触发pureFunction1Internal,重新计算绑定的值:

最终调用到我实现的Mock pipe: