Search code examples
angulartestingjasmine

While testing angular code, how do I mock large parameters of functions?


I have ts functions which take parameters of specific interface types. In some scenarios those interfaces are very large, 30-40 lines. So while testing this function, I have to pass it the argument as an object of this interface. But every time I have changes in the interface, I have to change these stubs. Is there a way to mock this parameters


Solution

  • Yes, I use the as any typecast to help me in this scenario.

    interface Person {
      name: string;
      height: number;
      age: number;
    }
    
    class Logger {
      logNameIfAndy(person: Person) {
        if (person.name === 'Andy') {
           console.log('Your name is Andy.');
        } else {
           console.log('Your name is not Andy.');
        }
      }
    }
    

    Then in a test, I don't have to mock out the height or age, just the properties I need.

    const logger = new Logger();
    // add the as any here to mock out only what is required and force it to be a
    // Person type
    logger.logNameIfAndy({ name: 'Andy' } as any);