簡體   English   中英

噴油器角度測試失敗?

[英]angular test fails at injector?

我有以下組成部分:

@Component({
  selector: 'app-comment-table',
  templateUrl: './comment-table.component.html',
  styleUrls: ['./comment-table.component.css']
})
export class CommentTableComponent implements OnInit {
  @Input() line: string;
  comments: Array<IComments>;
  constructor(private socketService: SocketService) {
    this.comments = [];
  }
  //some functions
}

我正在嘗試通過以下測試進行測試:

class mockSocket {
  getComments() { return Observable.of() }
};

describe('Comment Table Component', () => {
  let fixture, comp, el;
  let mockSock = new mockSocket();

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [Ng2SmartTableModule],
      declarations: [CommentTableComponent],
      providers: [
        { provide: SocketService, useValue: mockSock }],
    });
  });

  it('should call service',
    inject([CommentTableComponent], (cmp: CommentTableComponent) => {
      spyOn(mockSock, 'getComments');
      cmp.ngOnInit();
      expect(mockSock.getComments).toHaveBeenCalled();
    }));
});

但是,此測試失敗並顯示錯誤消息:

注入錯誤(webpack:///~/@angular/core/@angular/core.es5.js:1231:21 <-client / src / test.ts:6040:86)在noProviderError上的[ProxyZone](webpack: ///~/@angular/core/@angular/core.es5.js:1269:0 <-client / src / test.ts:6078:12)[ProxyZone]

我認為該組件只需要向我提供的SocketService即可,但是該錯誤看起來好像缺少了提供程序? 我究竟做錯了什么?

.compileComponents()添加到TestBed創建中,並將其包裝在async()函數中:

beforeEach( async( () => {
    TestBed.configureTestingModule( {
        imports: [ Ng2SmartTableModule ],
        declarations: [ CommentTableComponent ],
        providers: [
            { provide: SocketService, useValue: mockSock }
        ],
    } ).compileComponents();
} ) );

如果這還不夠,還可以將inject包裝在async()中:

it('should call service',
    async( inject( [ CommentTableComponent ], ( cmp: CommentTableComponent ) => {
        spyOn( mockSock, 'getComments' );
        cmp.ngOnInit();
        expect( mockSock.getComments ).toHaveBeenCalled();
} ) ) );

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM