Search code examples
angularunit-testingkarma-jasmineangular-unit-test

Angular Unit Test - What is the difference between new Service() and Testbed.inject()?


On Angular's website, we can see two ways to write unit test of Service.

The first is to instantiate the service by new Service.

let service: ValueService; beforeEach(() => { service = new ValueService(); });

Second, is instantiate the service by TestBed.

beforeEach(() => {
    TestBed.configureTestingModule({ providers: [ValueService] });
    service = TestBed.inject(ValueService);
});

Can anybody tell me what's the difference between these two methods, when should and should not use each of them, thanks a lot!


Solution

  • If my tested service have constructor using another service or router, can I still use new Service()

    In this case you will create other services also and pass it in the constructor. Instead of using angular dependency management you wire it manually.

    It says you can use new Service when you won't call the constructor a subsequent time. Does that mean I can't call this service in other component's unit test (in same project) that provides this service in it's Testbed?

    I think they just mean that if you need to keep calling new Service for each place it's not efficient and better to use Testbed where one instance is created and it is returned every time.