单位测试 - 指令中模拟组件上的错误消息。 '组件'被宣布,但其价值永远不会阅读
我试图嘲笑一个组件来测试setCursorPositive -Diroveditive指令,但是我会声明错误'组件',但其值永远不会读取。
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 { }
I'm trying to mock a component to unit test the SetCursorPositionDirective directive, but I'm getting the error '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 { }
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您遇到的错误是因为您的组件变量从未在任何地方实际使用。它只有定义并分配了一个值,但再也没有使用过。除非您打算在单元测试中使用它,否则您真的不需要变量。
The error you are getting is because your component variable is never actually used anywhere. Its only ever defined and then assigned a value but never used again. You really dont need the variable at all unless you plan to use it in your unit tests.
感谢您的信息。我认为,通过为变量分配一个值,这将不会发生。
Thanks for the information. I thought that by assigning a value to the variable, this would not happen.