Issue setting up dependencies for Angular testbed with ng bootstrap elements despite importing NgbModule.forRoot()

问题: I'm having trouble setting up the dependencies for a component that includes an ng bootstrap modal. The following code is from a test project that isolates the issue. The c...

问题:

I'm having trouble setting up the dependencies for a component that includes an ng bootstrap modal. The following code is from a test project that isolates the issue. The component works and runs with no errors when the website is served but there seems to be a dependency issue with the tests. I'm using the NgbModal service to open and close the modal within the component. Here's the setup of the component:

@Component({
  selector: 'app-main-component',
  templateUrl: './main.component.html',
  styleUrls: ['./main.component.css'],
  providers: [ NgbModal ]
})
export class MainComponent implements OnInit {

  constructor(private modalService: NgbModal) { }

and here's where the dependencies are set up in the app.module.ts:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppComponent } from './app.component';
import { MainComponent } from './main/main.component';
import { NgbModule } from '@ng-bootstrap/ng-bootstrap';

@NgModule({
  declarations: [
    AppComponent,
    MainComponent
  ],
  imports: [
    BrowserModule,
    NgbModule.forRoot()
  ],
  bootstrap: [AppComponent]
})

and the dependencies for the testbed are set up in the main.component.ts file here:

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ MainComponent ],
      imports: [ NgbModule.forRoot(), BrowserModule ],
      providers:[ NgbModal ]
    })
    .compileComponents();
    component = TestBed.get(MainComponent);
    modalService = TestBed.get(NgbModal);
  }));

When I try to run the tests it's giving me this error

Failed: StaticInjectorError(DynamicTestModule)[NgbModal -> NgbModalStack]: 
  StaticInjectorError(Platform: core)[NgbModal -> NgbModalStack]: 
    NullInjectorError: No provider for NgbModalStack!

which seems to imply there's a missing dependency. With errors like this in the main app it seems like it's usually caused by the NgbModule.forRoot() not getting imported but it's in the imports for the test. Thank you for your time.


回答1:

Turns out the issue wasn't in my main component spec file, it was an issue running the test for my app component spec file. Since the component was used in the main app component it needed to have the same imports in the app component spec file.

  • 发表于 2018-07-10 18:58
  • 阅读 ( 1408 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除