How to fix beforeEachProviders (deprecated on RC4)

2019-02-21 08:07发布

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

3条回答
来,给爷笑一个
2楼-- · 2019-02-21 08:33

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

查看更多
冷血范
3楼-- · 2019-02-21 08:37

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

查看更多
冷血范
4楼-- · 2019-02-21 08:40

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);
  });
});
查看更多
登录 后发表回答