Search code examples
angularunit-testingmockingng-mocks

How to Mock a the same method with different input/returns with NgMocks?


I'm doing some tests, and using ng-mocks for our store as well as ng-mocks for the testing.

I'm currently one service, that is subscribing to one selector of the store:

  async initialize() {
    const elementId = await firstValueFrom(this.store.select(SomeState.someId));
    //[...]
    const someOtherElement= await firstValueFrom(this.store.select(SomeOtherState.someOtherElement));

    //Do something with the two elements
    //[...]    
  }

I've been able to mock such select before:

MockInstance(Store, 'select', () => of('some-id'));

But my issue here is that I should return something different depending on if the select has SomeState.someId as selector or if it has SomeOtherState.someOtherElement as selector.

Ideally, it would be great if I could something like the C# Moq library, that would allow me to specify 2 different versions:

Like

MockInstance(Store, 'select', (SomeState.someId) => of('some-id'));
MockInstance(Store, 'select', (SomeOtherState.someOtherElement) => of('some-other-element'));

But it doesn't seems to work that way


Solution

  • You should consider here a spy with switch options. For example, jasmine.withArgs

    Then your code can be like:

    const spy = MockInstance(Store, 'select', jasmine.createSpy());
    
    spy.withArgs(SomeState.someId)
      .and.returnValue(of('some-id'));
    
    spy.withArgs(SomeOtherState.someOtherElement)
      .and.returnValue(of('some-other-element'));
    
    // the rest of your test.