How to fix beforeEachProviders (deprecated on RC4)
Asked Answered
B

3

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'?

Blakeslee answered 1/7, 2016 at 2:22 Comment(0)
S
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

Sphene answered 1/7, 2016 at 3:3 Comment(6)
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!Blakeslee
provide() has been deprecated, but do you use instead?Mame
@Mame A plain object, see the difference stackoverflow.com/review/suggested-edits/12924184Sidwell
It appears that addProviders is gone at rc.6. Not sure what to use instead yet.Reasonless
How to fix it in rc.6? beacause addProvider was removed from @angular/core/testing.Enarthrosis
You need to use TestBed.configureTestingModule instead. Here's an exampleSphene
F
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

Favor answered 12/12, 2016 at 18:52 Comment(0)
P
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);
  });
});
Preoccupation answered 24/7, 2017 at 21:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.