Angular单元测试FormGroup对比出现Function to equal Function错误
问题根因
你直接使用toEqual对比两个独立实例化的FormGroup对象是错误的。FormGroup、FormControl属于Angular响应式表单的内置类,实例生成时会自动挂载很多内部私有方法(比如报错中提到的_onCollectionChange),这些方法属于不同的函数引用,哪怕两个FormGroup的业务逻辑完全一致,Jasmine做深度全量对比时也会判定不相等。
正确测试方案
你的服务核心逻辑是根据传入的问题配置,生成对应初始值、对应验证规则的表单组,单元测试只需要验证这两个核心逻辑符合预期即可,不需要对比实例的全量属性,修改后的测试用例参考如下:
it('creates toFormGroup successfully', () => { const mockedQuestions = [ {value: undefined, key: 'name', label: 'Name', required: true, order: 1, group: 1, controlType: 'textbox', type: 'text'}, {value: undefined, key: 'username', label: 'Username', required: false, order: 1, group: 2, controlType: 'textbox', type: 'text'}, {value: 'john@doe.com', key: 'email', label: 'Email', required: true, order: 2, group: 1, controlType: 'textbox', type: 'email'} ] const res = service.toFormGroup(mockedQuestions); // 1. 校验所有控件初始值符合预期 expect(res.value).toEqual({ name: null, username: null, email: 'john@doe.com' }); // 2. 校验所有控件的验证规则符合预期(Angular 12及以上版本支持hasValidator方法) expect(res.get('name')?.hasValidator(Validators.required)).toBeTrue(); expect(res.get('username')?.hasValidator(Validators.required)).toBeFalse(); expect(res.get('email')?.hasValidator(Validators.required)).toBeTrue(); // 可选:校验表单整体有效性符合预期 expect(res.invalid).toBeTrue(); // name为空且必填,整体表单无效 });
如果你的Angular版本低于12,没有hasValidator方法,也可以通过主动给控件赋值后校验valid状态的方式间接验证验证规则是否生效。
内容的提问来源于stack exchange,提问作者mr3k
相关产品推荐
相关产品推荐

