angular - 如果指令属性为真,则对需要添加 css 类的指令进行单元测试
问题描述
您好,我在 dom 中的元素中测试指令时遇到问题,如果指令值为 true,则应将 css 类设置为特定的类名,否则设置为另一个类名
收到以下错误无法读取 null 的属性“属性”
规格
import { Component } from '@angular/core';
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { UiSetLabelStateDirective } from './set-label-state.directive';
// Simple test component that will not in the actual app
@Component({
template: `
<p [setLabelState]="true">Bold label</p>
<p [setLabelState]="false">normal label</p>
<p>Testing Directives is awesome!</p>
`,
})
class TestComponent {}
describe('UiSetLabelStateDirective', () => {
let component: TestComponent;
let fixture: ComponentFixture<TestComponent>;
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [TestComponent, UiSetLabelStateDirective],
});
fixture = TestBed.createComponent(TestComponent);
component = fixture.componentInstance;
});
test('should add font-weight-bold class if setLabelState is true', () => {
const elements = fixture.debugElement.query(By.css('p[setLabelState=true]'));
expect(elements.properties.className).toEqual('font-weight-bold');
});
test('should add unselected class if setLabelState is false', () => {
const elements = fixture.debugElement.query(By.css('p[setLabelState=false]'));
expect(elements.properties.className).toEqual('unselected');
});
});
指令.ts
import { Directive, ElementRef, Input, OnInit, Renderer2 } from '@angular/core';
@Directive({
selector: '[setLabelState]',
})
export class UiSetLabelStateDirective implements OnInit {
@Input() public setLabelState: boolean;
private element: HTMLInputElement;
constructor(private renderer: Renderer2, private elementReference: ElementRef) {
this.element = this.elementReference?.nativeElement as HTMLInputElement;
}
public ngOnInit(): void {
if (!this.element) {
return;
}
if (this.setLabelState) {
this.renderer.addClass(this.element, 'font-weight-bold');
} else {
this.renderer.addClass(this.element, 'unselected');
}
}
}
感谢您的帮助和回复
解决方案
推荐阅读
- python - 在选择字段上使用 xlsxwriter strings_to_numbers 选项
- generics - 这个协变类的用例?
- latex - LaTeX 列表不可见
- python-3.x - 无法导入 pyperclip 模块
- elixir - 长生不老药苦艾酒 input_object
- android - 尝试检索维度时出现错误 NotFoundException
- xml - 使用 ELK 解析复杂的 XML 文件
- java - gradle构建时出现StackOverflowError
- reactjs - Recharts - 在条形图的工具提示上添加逗号到数字
- jquery - 如何在更改功能的文档中引用“$(this)”?