Angular 开玩笑测试“找不到名称 'By'”。

Angular Jest testing `Cannot find name 'By'.`

我正在使用 Jest.JS 和 Angular。当我尝试测试该指令时,出现错误:

Cannot find name 'By'.

src/app/directives/error-highlighter.directive.spec.ts:33:46 - error TS2304: Cannot find name 'By'.

    33         inputEl = fixture.debugElement.query(By.css('input'));

用我的 node_module - 安装东西需要什么?

directive.spec 文件:

import { ErrorHighlighterDirective } from './error-highlighter.directive';
import { Directive, ElementRef, SimpleChanges, HostListener, Renderer2, Component, DebugElement } from '@angular/core';
import { NgControl, FormGroup, FormsModule, FormControl, ReactiveFormsModule } from '@angular/forms';
import { TestBed, ComponentFixture } from '@angular/core/testing';

@Component({
    template: `<input errorHighlighter formControlName="Url" type="text">`
})
class TestHighlighterComponent { }



describe('ErrorHighlighterDirective', () => {

    let component: TestHighlighterComponent;
    let fixture: ComponentFixture<TestHighlighterComponent>;
    let inputEl: DebugElement;

    const fg: FormGroup = new FormGroup({
        'Url': new FormControl('')
    });

    beforeEach(() => {
        TestBed.configureTestingModule({
            declarations: [TestHighlighterComponent, ErrorHighlighterDirective],
            imports: [FormsModule, ReactiveFormsModule],
            providers: [
                { provide: NgControl, useValue: fg }
            ]
        });
        fixture = TestBed.createComponent(TestHighlighterComponent);
        component = fixture.componentInstance;
        inputEl = fixture.debugElement.query(By.css('input'));

    });


    it('should create an instance', () => {
        const directive = new ErrorHighlighterDirective(inputEl, fg, Renderer2);
        expect(directive).toBeTruthy();
    });

});

您需要从 angular.platform-browser

导入 By
import { By } from '@angular/platform-browser'

您可以进一步阅读 here