【问题标题】:Angular Jest testing `Cannot find name 'By'.`Angular Jest 测试`找不到名称'By'。`
【发布时间】:2020-02-15 00:07:03
【问题描述】:

我将 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();
    });

});

【问题讨论】:

  • 你能分享你的整个spec.ts文件吗?
  • @jess - 添加了规范文件
  • 对不起,我的意思是error-highlighter.directive.spec.ts
  • @jess - 添加了指令规范文件
  • 我想你忘了import {By} from "@angular/platform-browser";

标签: angular jestjs angular-test angular-jest


【解决方案1】:

你需要从 angular.platform-b​​rowser 导入 By

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

您可以进一步阅读here

【讨论】:

  • 是只有By还是需要导入所有的选择器?我在哪里可以找到完整的规格?
猜你喜欢
  • 1970-01-01
  • 2017-03-25
  • 2016-12-25
  • 2017-12-30
  • 2021-01-26
  • 1970-01-01
  • 1970-01-01
  • 2021-03-14
  • 1970-01-01
相关资源
最近更新 更多