我正在开发一个应该生成查询构建器表单的项目。主要组件是 SearchComponent,动态添加的组件是 SearchParameterComponent。我正在尝试为该组件编写单元测试。我附上了下面的代码。
search.component.spec.ts
import { ComponentFactoryResolver } from '@angular/core';
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { BrowserDynamicTestingModule } from '@angular/platform-browser-dynamic/testing';
import { RouterTestingModule } from '@angular/router/testing';
import { environment } from 'src/environments/environment';
import { AdDirective } from './ad.directive';
import { SearchParameterComponent } from './search-parameter/search-parameter.component';
import { SearchComponent } from './search.component';
import { SearchComponentService } from './serach-component.service';
describe('SearchComponent', () => {
let component: SearchComponent;
let fixture: ComponentFixture<SearchComponent>;
let componentFactoryResolver:ComponentFactoryResolver;
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [RouterTestingModule],
declarations: [SearchComponent,SearchParameterComponent,AdDirective],
providers: [
{
provide: SearchComponentService,
useClass: SearchComponentService,
},
]
}).compileComponents();
await TestBed.overrideModule(BrowserDynamicTestingModule, {
set: {
entryComponents: [SearchParameterComponent]
}
}).compileComponents();
TestBed.compileComponents();
});
beforeEach(() => {
fixture = TestBed.createComponent(SearchComponent);
component = fixture.componentInstance;
componentFactoryResolver = fixture.debugElement.injector.get(ComponentFactoryResolver);
fixture.detectChanges();
});
it('When you hit the add button a new parameter selector should be added', () => {
const addButton: HTMLSelectElement =
fixture.nativeElement.querySelector('#add-button');
const numberOfTimesButtonIsClicked = Math.floor(Math.random() * 10) + 1;
let i = 1;
for (i; i <= numberOfTimesButtonIsClicked; i++) {
addButton.dispatchEvent(new Event('click'));
fixture.detectChanges();
}
i = 1;
for (i; i <= numberOfTimesButtonIsClicked; i++) {
expect(
fixture.nativeElement.querySelector('#' + (i + 1).toString())
).not.toBeNull();
}
});
});
所以有一个 id 为“add-button”的按钮,当它被点击时,一个新的 SearchParameterComponent 被动态添加。代码的编写方式是,如果有 n 次点击,将生成 n 个 id 为 2 到 n+1 的组件。
算法
1) numberOfTimesButtonIsClicked<-random number from 1 to 10 representing number of times the button is clicked
2)simulate clicking the button numberOfTimesButtonIsClicked times
3)Check if components with id's from 2 to numberOfTimesButtonIsClicked+1 is present
当我运行测试时,出现以下错误
SyntaxError:无法在“元素”上执行“querySelector”:“#2”不是有效的选择器。
我知道这个问题可能有点难以理解,但如果有人能解决它,那将非常有帮助
我反应迅速,会很快提供您需要的任何其他代码