错误:StaticInjectorError(DynamicTestModule)[NotificationsComponent

时间:2018-05-21 12:57:40

标签: angular unit-testing typescript testing

运行ng test

完全错误:

  

错误:StaticInjectorError(DynamicTestModule)[NotificationsComponent

     

AuthService]:StaticInjectorError(Platform:core)[NotificationsComponent AuthService]:

     

NullInjectorError:没有AuthService的提供者!

     

预计未定义为真正的。

     

错误:预期未定义为真正的。

     

在堆栈(http://localhost:9876/base/node_modules/jasmine-core/lib/jasmine-core/jasmine.js:2176:17

     

在buildExpectationResult(http://localhost:9876/base/node_modules/jasmine-core/lib/jasmine-core/jasmine.js:2146:14

     

在Spec.expectationResultFactory(http://localhost:9876/base/node_modules/jasmine-core/lib/jasmine-core/jasmine.js:766:18

     

在Spec.addExpectationResult(http://localhost:9876/base/node_modules/jasmine-core/lib/jasmine-core/jasmine.js:444:34

     

at Expectation.addExpectationResult(http://localhost:9876/base/node_modules/jasmine-core/lib/jasmine-core/jasmine.js:710:21

     

at Expectation.toBeTruthy(http://localhost:9876/base/node_modules/jasmine-core/lib/jasmine-core/jasmine.js:2099:12

     

at Object。 (http://localhost:9876/_karma_webpack_/webpack:/C:/../webTest/src/app/components/notifications/notifications.component.spec.ts:97:23

     

在ZoneDelegate.webpackJsonp ... / .. / .. / .. / zone.js / dist / zone.js.ZoneDelegate.invoke   (http://localhost:9876/_karma_webpack_/webpack:/C:/C:/../webTest/node_modules/zone.js/dist/zone.js:388:1

     

在ProxyZoneSpec.webpackJsonp ... / .. / .. / .. / zone.js / dist / proxy.js.ProxyZoneSpec.onInvoke   (http://localhost:9876/_karma_webpack_/webpack:/C:/../webTest/node_modules/zone.js/dist/proxy.js:79:1

     

在ZoneDelegate.webpackJsonp ... / .. / .. / .. / zone.js / dist / zone.js.ZoneDelegate.invoke   (http://localhost:9876/_karma_webpack_/webpack:/C:/../webTest/node_modules/zone.js/dist/zone.js:387:1

我的代码服务:

describe('Component: Auth', () => {


    let component: AuthService;

    let fixture: ComponentFixture<AuthService>;


    beforeEach(() => {

        TestBed.configureTestingModule({

            declarations: [AuthService]

        })

        fixture = TestBed.createComponent(AuthService);

        component = fixture.componentInstance;

    });

});

你能问我,问题是什么?

2 个答案:

答案 0 :(得分:5)

使用如下:

服务应位于providers数组中。

describe('Component: Auth', () => {
let component: AuthService;
let fixture: ComponentFixture<AuthService>;

  beforeEach(() => {
    TestBed.configureTestingModule({
        declarations: [],
        providers: [AuthService] // **Like this.**
    })
    fixture = TestBed.createComponent(AuthService);
    component = fixture.componentInstance;
  });

});

答案 1 :(得分:0)

您必须实例化服务:let service = new AuthService();,无需调用&#34; createComponent&#34;等等。

https://angular.io/guide/testing#service-tests