单元测试因Angular中的NullInjectorError而失败

时间:2019-03-20 13:30:44

标签: angular unit-testing

我是Angular的新手,在了解DI的工作原理时我缺少一些东西。我目前正在尝试通过单元测试。

这是测试代码;

document.querySelectorAll('.section-dynamique-fr').forEach( (e) => {

    ClassicEditor
        .create( document.querySelector('#' + e.id), {
            // toolbar: [ 'heading', '|', 'bold', 'italic', 'link' ]
        } )
        .then( editor => {
            window.editor = editor;
            thisEditor = editor;
        } )
        .catch( err => {
            console.error( err.stack );
        } );

    console.log(e); //This gives me the textarea
    console.log(e.nextElementSibling); //This should gives me the div with class ck-editor but instead gives me the div with class .textarea-saved-content-fr

这是正在测试的代码;

import { TestBed } from '@angular/core/testing';
import { HttpClientModule, HttpClient } from '@angular/common/http'
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';
import { InjectionToken } from '@angular/core';
import { UserService } from './user.service';

export const BASE_URL = new InjectionToken<string>('BASE_URL');

describe('UserService', () => {
  beforeEach(() => TestBed.configureTestingModule({
    imports: [
      HttpClientTestingModule,
    ],
    providers: [
      { provide: BASE_URL, useValue: 'http://localhost' },
      UserService,
      HttpClient
    ]
  }));

  it('should be created', () => {
    const service: UserService = TestBed.get(UserService);
    expect(service).toBeTruthy();
  });
});

这是我的错误;

  

错误:StaticInjectorError(DynamicTestModule)[BASE_URL]:
  StaticInjectorError(平台:核心)[BASE_URL]:       NullInjectorError:没有BASE_URL的提供程序!

为什么会出现此错误,我该怎么办才能纠正它?

1 个答案:

答案 0 :(得分:1)

更换 { provide: BASE_URL, useValue: 'http://localhost' }{ provide: 'BASE_URL', useValue: 'http://localhost'}