App testing return "NullInjectorError: No provider for Location!"

An alternative to NullInjectorError: No provider for Location! during the testing is to import RouterTestingModule.

ex. mycomponent.spec.ts:

    import { RouterTestingModule } from '@angular/router/testing';
    ...
    beforeEach(() => TestBed.configureTestingModule({
            imports: [ RouterTestingModule ]
    }));

In my case, I was using the RouterTestingModule already which should not raise this error. I have imported Location from the wrong place so the error has appeared. 'Location' should be imported from here:

import {Location} from '@angular/common';

In your imports you should only import RouterTestingModule like this:

TestBed.configureTestingModule({
      imports: [
        RouterTestingModule.withRoutes(
          [
            {path: 'add', component: DummyComponent, pathMatch: 'full'}
          ]
        )
      ],

and then you can use Location like this:

it('Should navigate to / before + button click', () => {
    const location: Location = TestBed.get(Location);
    expect(location.path()).toBe('');
  });

Just don't forget to import Location from @angular/common


Fixed it: all I needed to do was to import RouterModule.forRoot([]), which seems to be a common mistake as it fixes a lot of StaticInjectorError(DynamicTestModule) errors.