17

Ive just upgraded Angular2 from RC3 to RC4 ...

import {
  expect, it, iit, xit,
  describe, ddescribe, xdescribe,
  beforeEach, beforeEachProviders, withProviders,
  async, inject
} from '@angular/core/testing';

In my unit test I have the following code ...

beforeEachProviders(() => [
    {provide: Router, useClass: MockRouter}
]);

This works fine but since moving to RC4 I have a deprecation warning on beforeEachProviders.

Anyone know what the new way of doing things is? Or should I import beforeEachProviders from somewhere else instead of '@angular/core/testing'?

danday74
  • 52,471
  • 49
  • 232
  • 283

3 Answers3

21

You will need to import addProviders from @angular/core/testing.

Instead of:

beforeEachProviders(() => [
    {provide: Router, useClass: MockRouter}
]);

You'll want to do this:

beforeEach(() => {
    addProviders([
        {provide: Router, useClass: MockRouter}
    ])
});

Source: RC4 Changelog

Edd
  • 25
  • 4
mifish
  • 314
  • 2
  • 5
  • 1
    Thank you ever so much - you use of addProviders is correct - your use of provide is not necessary (and probably deprecated). Your reference to the change log is essential - many many thanks. So helpful I am extremely thankful. Saved me so much time! – danday74 Jul 01 '16 at 10:14
  • 1
    provide() has been deprecated, but do you use instead? – wholladay Jul 06 '16 at 16:55
  • 1
    @wholladay A plain object, see the difference http://stackoverflow.com/review/suggested-edits/12924184 – Estus Flask Jul 08 '16 at 03:56
  • 4
    It appears that addProviders is gone at rc.6. Not sure what to use instead yet. – Josh Werts Sep 01 '16 at 14:55
  • 2
    How to fix it in rc.6? beacause addProvider was removed from @angular/core/testing. – ljofre Sep 09 '16 at 22:41
  • 3
    You need to use TestBed.configureTestingModule instead. Here's an [example](http://stackoverflow.com/questions/38914457/angular-2-testbed-with-mocks) – mifish Sep 14 '16 at 17:27
14

After reviewing a few other documents, it appears you want:

beforeEach(() => TestBed.configureTestingModule({
        providers: [
            { provide: Service, useClass: MockService }
        ]})
    );

Source: https://angular.io/guide/dependency-injection

shohrukh
  • 2,989
  • 3
  • 23
  • 38
Tye2545
  • 191
  • 2
  • 8
1

Here's a complete example, for a Window reference service:

import { TestBed, inject } from '@angular/core/testing';
import { WindowRef } from './window-ref';

describe('WindowRef', () => {
  let subject: WindowRef;

  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [
        WindowRef
      ]});
  });

  beforeEach(inject([WindowRef], (windowRef: WindowRef) => {
    subject = windowRef;
  }));

  it('should provide a way to access the native window object', () => {
    expect(subject.nativeWindow).toBe(window);
  });
});
Steve Brush
  • 2,911
  • 1
  • 23
  • 15