How to test Angular pipes

Angular pipes transform display values in templates, and testing them ensures your data formatting logic works correctly with edge cases and unexpected inputs. As the creator of CoreUI with over 12 years of Angular experience since 2014, I’ve built and tested numerous custom pipes for enterprise applications. Testing pipes is straightforward because they’re pure functions that take input and return transformed output without side effects. The approach involves instantiating the pipe directly and calling its transform method with various test inputs.

Instantiate the pipe class directly and test its transform method with various inputs.

import { TruncatePipe } from './truncate.pipe'

describe('TruncatePipe', () => {
  let pipe: TruncatePipe

  beforeEach(() => {
    pipe = new TruncatePipe()
  })

  it('should create an instance', () => {
    expect(pipe).toBeTruthy()
  })

  it('should truncate long text', () => {
    const text = 'This is a very long text that needs truncation'
    const result = pipe.transform(text, 20)
    expect(result).toBe('This is a very long...')
  })

  it('should not truncate short text', () => {
    const text = 'Short text'
    const result = pipe.transform(text, 20)
    expect(result).toBe('Short text')
  })

  it('should handle empty string', () => {
    expect(pipe.transform('', 10)).toBe('')
  })

  it('should handle null and undefined', () => {
    expect(pipe.transform(null, 10)).toBe('')
    expect(pipe.transform(undefined, 10)).toBe('')
  })

  it('should use custom suffix', () => {
    const text = 'This is a long text'
    const result = pipe.transform(text, 10, '---')
    expect(result).toBe('This is a---')
  })
})

Best Practice Note

Always test edge cases like null, undefined, empty strings, and boundary values. For pipes with dependencies, use TestBed to inject the pipe instead of direct instantiation. Test all parameters and optional arguments to ensure the pipe handles various configurations. For async pipes or pipes using services, mock dependencies appropriately. This is how we test pipes in CoreUI for Angular—comprehensive coverage of all code paths including edge cases to ensure robust data transformation in production dashboards.


Speed up your responsive apps and websites with fully-featured, ready-to-use open-source admin panel templates—free to use and built for efficiency.


About the Author

Subscribe to our newsletter
Get early information about new products, product updates and blog posts.
How to Use JavaScript setTimeout()
How to Use JavaScript setTimeout()

What is the Difference Between Null and Undefined in JavaScript
What is the Difference Between Null and Undefined in JavaScript

How to Clone an Object in JavaScript
How to Clone an Object in JavaScript

How to limit items in a .map loop in JavaScript
How to limit items in a .map loop in JavaScript

Answers by CoreUI Core Team