How to fix beforeEachProviders (deprecated on RC4)

谁说我不能喝 提交于 2019-12-19 14:44:40

问题


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


回答1:


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




回答2:


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:


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);
  });
});


来源:https://stackoverflow.com/questions/38136059/how-to-fix-beforeeachproviders-deprecated-on-rc4

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!