Search code examples
serviceng-mocks

ng-mocks - how to create a mock of a service, outside of a Component test bed context?


I know how to work with mocked services injected into a Component, if I am testing the Component. But if I am testing a Service that injects a SubService, I only need

const testedService = new Service(mockSubService);

Is there a way to use ng-mocks to get a mock of the SubService, ideally with all MockInstance effective ?

I have tried various variants of code like this:

MockInstance(SubService, 'someProperty', () => 10, 'get');
MockBuilder().mock(SubService);
const mockSubService = TestBed.inject(SubService);

or this:

MockBuilder().mock(SubService, {someProperty: 10});
const mockSubService = TestBed.inject(SubService);

but in both cases, "someProperty" is not mocked - the actual SubService implementation is returned by TestBed.

I have a feeling I am missing something very simple about ng-mocks, but the online help is a bit confusing. I also know of MockService, but apparently that's not supposed to be used in cases like mine, and also it doesn't set up spies.


Solution

  • It sounds like you need MockService and MockProvider.

    What you describe is covered in ng-mocks documentation about how to test providers with dependencies.

    beforeEach(() =>
      MockBuilder(Service, ServiceModule)
        // Service2 is provided / imported in ServiceModule
        .mock(Service2, {
          trigger: () => 'mock2',
        })
        // Service3 will be provided in TestBed
        .provide(MockProvider(Service3, {
          trigger: () => 'mock3',
        })
    );
    

    If you need spies, you can use jasmine.createSpy().and.returnValue('mock2') instead of () => 'mock2'.