Angular: TestCase For Custom Pipe

tiana

I am new in Unit testing and i need help in writing TestCase for Sort Pipe in karma. My Custom Sorting Pipe is calling Methods Based on DirectionValue,In which the logic for sorting are.

@Pipe({
  name: 'sortBy'
})
export class SortByPipe implements PipeTransform {
transform(value[], direction:string){

    if (direction === 'desc'){
      this.descendingSort(value);
    }
    else if(direction === 'asc'){
      this.ascendingSort(value);
    }
    return value;
  }      

First Case: want to check If it's Calling right Method based on direction value or not.

Second Case: check the result of sort.

I tried to write for something like this for second case.

    const direction = 'asc';
    const pipe = new SortByPipe();
    const result = pipe.transform([4,3,2,1], direction);
    expect(result).toBe([1,2,3,4]);

Please Help me understand How i can Solve it. Thanks in Advance

Aleksi

I think there are two answers to this question:

  1. checking the called method

You can do something called spying in Jasmine with Jasmine Spies (https://jasmine.github.io/api/edge/Spy.html). This allows you to sort of like tap in to some method and tinker with it like returning a mocked value etc. It also keeps track on how many times the method was called:

const direction = 'asc';
const pipe = new SortByPipe();
spyOn(pipe, 'ascendingSort')

const result = pipe.transform([4,3,2,1], direction);

expect(result).toBe([1,2,3,4]);
expect(pipe.ascendingSort).toHaveBeenCalledTimes(1);
  1. Don't mind about inner workings of the function but about inputs and outputs

The ascending and descenting functions are part of the transform functions implementation (if not used else where) so it doesn't matter what was happening inside the function. What matter is what is the input and expected output. So to test a case like this you would just test both use cases:

it('should sort in ascending order', () => {
    const pipe = new SortByPipe();
    const result = pipe.transform([4,3,2,1], 'desc');

    expect(result).toBe([1,2,3,4]);
})
  
it('should sort in descending order', () => {
    const pipe = new SortByPipe();
    const result = pipe.transform([1,2,3,4], 'asc');

    expect(result).toBe([4,3,2,1]);
})

You really don't care what happens inside the test. You don't want to fix your tests if you decide to change from two functions to one like this.sort(value, direction) inside the transform function. If you however still think that inner functionality should be tested that's a good indicator your function is doing too much stuff. So in that case break it to smaller functions and write separate tests for those functions to keep tests isolated.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related