【问题标题】:How can Jasmine use FormGroup super constructor when called in ngOnInit?Jasmine 在 ngOnInit 中调用时如何使用 FormGroup 超级构造函数?
【发布时间】:2019-04-02 02:46:37
【问题描述】:

我已经定义了自己的表单类,它使用以下构造函数扩展了 FormGroup:

public constructor(/* params */) {
    function myValidator(): ValidatorFn {
      //return validator function
    }

    super({ /* controls */}, [myValidator()]);
  }

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

TypeError:没有'new'就不能调用类构造函数FormGroup

它是在我的组件的 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();
    });
  });
});

【问题讨论】:

    标签: angular unit-testing jasmine typeerror


    【解决方案1】:

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

    compilerOptions 我有"target": "es5",当我删除时我不再收到错误。

    【讨论】:

      猜你喜欢
      • 2021-06-29
      • 2016-07-16
      • 2012-10-27
      • 2011-01-24
      • 1970-01-01
      • 2021-11-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多