代码之家  ›  专栏  ›  技术社区  ›  Friso

在ngOnInit中调用时,Jasmine如何使用FormGroup超级构造函数?

  •  0
  • Friso  · 技术社区  · 6 年前

    public constructor(/* params */) {
        function myValidator(): ValidatorFn {
          //return validator function
        }
    
        super({ /* controls */}, [myValidator()]);
      }
    

    当我运行我的应用程序时,它可以工作,但是当我为它运行单元测试时,它在超级构造函数上中断,我得到以下错误消息:

    它是在组件的ngOnInit函数中构造的,如下所示:

    ngOnInit() {
        this.myForm = new MyForm(/* args */);
        //call service
      }
    

    我的规范文件:

    let component: MyComponent;
    let fixture: ComponentFixture<MyComponent>;
    
    const myArray = ['object'];
    let myServiceMock: any;
    let getCallSpy: any;
    
    describe('ErdwwLoggingComponent', () => {
    
      beforeEach(async(() => {
        myServiceMock = jasmine.createSpyObj('MyService', ['getCall']);
        getCallSpy = myService.getCall.and.returnValue( of(myArray) );
    
        TestBed.configureTestingModule({
          declarations: [
            MyComponent
          ],
          providers: [
            { provide: MyService, useValue: myServiceMock }
          ]
        });
    
        TestBed.overrideComponent(MyComponent, {
          remove: {
            templateUrl: './my.component.html'
          },
          add: {
            template: '<div>test</div>'
          }
        });
    
        TestBed.compileComponents().then(() => {
          fixture = TestBed.createComponent(MyComponent);
          component = fixture.componentInstance;
        });
      }));
    
      //succeeds
      it('should have spies defined', () => {
        expect(myServiceMock.getCall).toBeDefined('myServiceMock.getCall not defined');
        expect(getCallSpy).toBeDefined('getCallSpy not defined');
      });
    
      describe('initialisation', () => {
        //succeeds
        it('should be defined', () => {
          expect(component).toBeDefined();
        });
    
        //fails
        it('should call getCall', () => {
          // I also tried explicitly calling component.ngOnInit();
          fixture.detectChanges(); // onInit()
    
          expect(myServiceMock.getCall).toHaveBeenCalled();
        });
      });
    });
    
    1 回复  |  直到 6 年前
        1
  •  0
  •   Friso    6 年前

    问题出在我的tsconfig.spec.json文件中。

    compilerOptions 我有 "target": "es5"