天天看點

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設計

繼續閱讀