天天看点

Angular单元测试里pipe的mock设计

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

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

/**
 * 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
 */      
Angular单元测试里pipe的mock设计
Angular单元测试里pipe的mock设计
Angular单元测试里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,重新计算绑定的值:

Angular单元测试里pipe的mock设计
Angular单元测试里pipe的mock设计

继续阅读