单元测试 - 指令中模拟组件的错误消息。 'component' 已声明,但其值从未被读取

Unit test - Error message on mock component in directive. 'component' is declared but its value is never read

我正在尝试模拟组件以对 SetCursorPositionDirective 指令进行单元测试,但出现错误 'component' is declared but its value is never read .

import { Component } from '@angular/core';
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { FormsModule } from '@angular/forms';
import { By } from '@angular/platform-browser';
import { SetCursorPositionDirective } from './set-cursor-position.directive';

describe('SetCursorPositionDirective', () => {
  let fixture: ComponentFixture<MockSetCursorPositionComponent>;
  let component: MockSetCursorPositionComponent;
  let input: HTMLInputElement;
  let directive: any;

  beforeEach(async () => {
    await TestBed.configureTestingModule({
      declarations: [SetCursorPositionDirective, MockSetCursorPositionComponent],
      imports: [FormsModule],
    });
    fixture = TestBed.createComponent(MockSetCursorPositionComponent);
    component = fixture.componentInstance;
    input = fixture.debugElement.query(By.css('input')).nativeElement;
    directive = new SetCursorPositionDirective();
  });

  it('should create an instance', () => {
    expect(directive).toBeTruthy();
  });
});

@Component({ template: '<input setCursorPosition>' })
export class MockSetCursorPositionComponent { }

您收到的错误是因为您的组件变量实际上从未在任何地方使用过。它只被定义然后分配一个值但再也没有使用过。你真的根本不需要这个变量,除非你打算在你的单元测试中使用它。

感谢您提供信息。我以为通过给变量赋值,就不会发生这种情况了。