angular - 在描述调用中获取夹具和组件值 - Angular 单元测试
问题描述
我正在为包含太多表单的 Web 应用程序编写单元测试。因此,为了代码优化,我正在创建一个将返回 function 的通用函数。该函数测试所有提供的表单字段(ReactiveFroms 方法)是否需要。
测试字段是否需要的函数。
通用功能.spec.ts:
export const componentTestFn = (formGroup: any, fields: Fields[], configurationOptions?) => () => {
describe('On required fields', () => {
beforeEach(() => {
if (configurationOptions) {
TestBed.configureTestingModule(configurationOptions)
.compileComponents();
}
});
fields.forEach(element => {
describe(element.name, () => {
it('should be a required field', () => {
let control = formGroup.get(element.formControlName);
if (element.nestedControl) {
control = control.get(element.nestedControl);
}
control.patchValue('');
expect(control.hasError('required')).toBeTruthy();
control.patchValue('Test');
expect(control.hasError('required')).toBeFalsy();
});
});
});
});
}
我正在使用 describe 子句从主规范文件中调用此函数。
main.component.spec.ts:
describe('Given a Physical Property Setup Component', () => {
let component: PhysicalPropertySetupComponent;
let fixture: ComponentFixture<PhysicalPropertySetupComponent>;
let fields: Fields[] = [
new Fields('','field1','',''),
new Fields('','field2','',''),
new Fields('','field3','',''),
new Fields('','field4','','')
];
beforeEach(() => {
TestBed.configureTestingModule({
....
});
fixture = TestBed.createComponent(PhysicalPropertySetupComponent);
component = fixture.componentInstance;
});
describe('Testing',common.componentTestFn(component.formGroup,fields));
});
但它给了我错误“TypeError:无法读取未定义的属性'formGroup'”。
我认为这是因为我们只能在it
子句中使用组件和夹具值。但我没有使用它,因为我componentTestFn
会替换它。同样,当我在里面调用这个函数时,it
它工作正常。
谁能告诉我如何formGroup
在描述中获得该值?任何帮助将不胜感激。
提前致谢!!
解决方案
不要将其放入 describe 函数,而是创建一个创建 describe 的函数:
export const componentTestFn = (
formGroup: any,
fields: Fields[],
configurationOptions?,
componentTested?
) => () => {...});
并这样称呼它:
componentTestFn(common.componentTestFn(component.formGroup, fields, undefined, 'Testing'));
推荐阅读
- firebase - 如何以安全的方式从 Cloud Tasks 调用 Firebase 函数?
- visual-studio-code - 将 google-java-format 从 Eclipse 导入 VSCode
- c++ - constexpr 初始化一个数组
- javascript - mongoose - 从 Model.find() 获取嵌套的对象数组并操作内部数组
- c# - 多个开发人员(Unity 帐户)是否可以使用带有 Unity 的 GitLab CI/CD?
- hibernate - 如何在 Hibernate 中使用自动模式生成覆盖而不是附加 SQL 模式定义?
- postgresql - 有没有办法在不向最终用户公开分数的情况下实现基于价值的分页
- python - Python-删除具有最低值的项目,如果两个值相同,则删除具有最低键的项目
- go - golang 中睡眠导致时间间隔相差十倍
- sql - 逐行迭代Oracle SQL查询结果,产生子查询