首页 > 解决方案 > 如果指令属性为真,则对需要添加 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');
    }
  }
}


感谢您的帮助和回复

标签: angularunit-testingangular2-directivests-jest

解决方案


推荐阅读