单元测试找不到按钮,它等于空



我正在尝试为可重用组件做单元测试,可重用组件有输入和输出。但是它似乎找不到按钮类。如果有办法的话,有没有办法不使用fixture

the error =TypeError: Cannot read properties of null

describe('SelectorComponent', () => {
let component: SelectorComponent;
let fixture: ComponentFixture<SelectorComponent>;
beforeEach(async () => {
component = new SelectorComponent();
});
beforeEach(() => {
fixture = TestBed.createComponent(SelectorComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});

it('should select a dimension when clicked', () => {
let selectors: Selector[] = [{
id: '1', 
name: 'Child ',
parent: 'Parent ',
sortOrder: 1,
icon: 'brain',
selected: true, 
children: []
}];
spyOn(component, 'selectSelector');
component.selectors = selectors;
let btn = fixture.debugElement.query(By.css('.selectors'));
btn.triggerEventHandler('click', null); 
fixture.detectChanges();
fixture.whenStable().then(() => {
expect(component.selectorSelected.emit).toHaveBeenCalled();
});
});
});
@Input() public selectors!: Selector[];
@Output() public selectoSelected = new EventEmitter<Dimension>();
constructor() { }
selectselectors(selector: Selector) {
this.selectoSelected.emit(selector);
}
<button
class="selector"
(click)="selectselectors(selectors)"
*ngFor="let selector of selectors"
>
<div class="name">{{ selector.name }}</div>
</button>

提前谢谢你,我是单元测试新手

我也试过没有夹具,但它似乎没有工作,它一直说按钮为空

您正在尝试查找具有选择器类的按钮By.css('.selectors')但是你的按钮只有类选择器(末尾无s)<button class="selector"

所以你必须删除by。css中的错别字并将其更改为By.css('.selector')

编辑:

如果在将选择器添加到组件(component.selectors = selectors;)后添加fixture.detectChanges();,则按钮将被渲染。这是因为ngFor不会在没有数组的情况下显示任何按钮。

你正在使用spyOn(component, 'selectSelector');,但你的组件只有selectselectors(打字错误)

你正在使用expect(component.selectorSelected.emit),但你的组件只有selectoSelected(打字错误)

相关内容