喷射器的角度测试失败?

时间:2017-04-28 11:36:24

标签: unit-testing angular typescript karma-jasmine angular-cli

我有以下组件:

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

但是,此测试失败并显示错误消息:

  

错误               at injectionError(webpack:///~/@angular/core/@angular/core.es5.js:1231:21&lt; - client / src / test.ts:6040:86)[ProxyZone]               在noProviderError(webpack:///~/@angular/core/@angular/core.es5.js:1269:0&lt; - client / src / test.ts:6078:12)[ProxyZone]

我认为组件只需要提供给它的SocketService,我提供的,但是这个错误看起来好像缺少了一个提供者?我做错了什么?

1 个答案:

答案 0 :(得分:0)

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