javascript - 如何测试 data-cy 指令?
问题描述
我不知道如何为此指令编写单元测试。你能帮助我吗?
import { Directive, ElementRef, Inject, Input, Renderer2 } from enter code here'@angular/core';
@Directive({
// tslint:disable-next-line:directive-selector
selector: '[data-cy]'
})
export class DataCyDirective {
@Input('data-cy') dataCy: string;
constructor(
private el: ElementRef,
private renderer: Renderer2,
@Inject('production') isProd: boolean
) {
if (isProd) {
renderer.removeAttribute(el.nativeElement, 'data-cy');
}
}
}
解决方案
我找到了解决方案
@Component({
template: `
<span id="expected" data-cy="elementCy"></span>
`
})
class DataCyDirectiveTestComponent implements OnInit {
constructor(@Inject('production') prod: boolean) {}
}
describe('DataCyDirective test version', () => {
let component: DataCyDirectiveTestComponent;
let fixture: ComponentFixture<DataCyDirectiveTestComponent>;
configureTestSuite();
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [DataCyDirectiveTestComponent, DataCyDirective],
providers: [{ provide: 'production', useValue: false }]
}).compileComponents();
});
beforeEach(() => {
fixture = TestBed.createComponent(DataCyDirectiveTestComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should NOT delete the data-cy attribute if production is not enabled', () => {
const el: ElementRef<HTMLElement> = fixture.debugElement.query(By.css('#expected'));
expect(el.nativeElement.getAttribute('data-cy')).not.toBeNull();
});
});
推荐阅读
- java - 如何在 apache camel 3.4.0 中实现 addRegistry(Registry registry) 方法?
- android - Kotlin - 将对象转换为 Parcelable
- maven - 声纳和 Maven 多模块项目 - 声纳可以分别分析每个模块吗?
- azure-devops - Azure 专用管道代理 .git 文件夹大小
- python - 如何将一个数据框的列与其他数据框的列进行比较并写入特定行
- java - 可怕的 Java SpringBoot 应用程序未使用 Docker-compose java.net.ConnectException 连接到 MySQL:连接被拒绝
- javascript - 在父容器 Avada 悬停时触发 Lottie 动画
- rest - 在 Azure 管道任务中运行 CURL GET 命令
- javascript - 无法从 d3 Funnel js 回调中访问角度变量
- matplotlib - 将轴添加到具有固定大小的图形