首页 > 解决方案 > Angular 6 从另一个组件接收输入以进行 Karma 单元测试

问题描述

所以我正在尝试为各种组件编写 Karma 测试,其中许多都从父组件接收输入。为了说明测试是如何工作的,我创建了一个包含 5 个不同文件的示例组作为各种教程:“random.test.component.child.html”、“random.test.component.child.ts”、“ random.test.component.html”、“random.test.component.ts”和“random.test.file.spec.ts”。

我想从一个组件接收输入并将值设置为另一个的变量([variable]="value")。我已经尝试访问应该通过 HTML 文件的输入直接设置的变量,但无济于事。

以下是文件的相关部分:

random.test.component.child.html(variableThatStoresTheDataThatTheChildReceives 显示为空白,除非手动设置)

<h2>Also, here's a thing that should load properly: {{variableThatStoresTheDataThatTheChildReceives}}</h2>

random.test.component.child.ts

@Input() variableThatStoresTheDataThatTheChildReceives: any;

random.test.component.html

<!-- The parents pass data to the children. -->
<random-test-child [variableThatStoresTheDataThatTheChildReceives]="dataFromTheParentToTheChild"></random-test-child>

random.test.component.ts

public dataFromTheParentToTheChild:any = "This is a test.";

random.test.file.spec.ts(在描述语句中)

it('Testing if receiving input from one component to another works properly', () => {

        childFixture.whenStable().then(() => {
            childFixture.detectChanges();
expect(childComponent.variableThatStoresTheDataThatTheChildReceives).toEqual("This is a test.");
        });
});

我希望从 HTML 组件接收的输入导致 childComponent.variableThatStoresTheDataThatTheChildReceives 等于“这是一个测试。”,但我得到“未定义”。我知道您可以像这样手动设置输入:

childComponent.variableThatWillHaveTheInputHardCodedKindOf = 'Manual Text';

但我正在尝试使用在未测试时传递给组件的数据来运行测试。

有没有办法做到这一点?

标签: angulartypescriptunit-testingkarma-runner

解决方案


您应该使用By.directive来获取您的子组件。像这样设置你的测试用例:

import { async, ComponentFixture, TestBed } from '@angular/core/testing';

import { RandomTestComponent } from './random-test.component';
import { RandomTestChildComponent } from '../random-test-child/random-test-child.component';
import { By } from '@angular/platform-browser';

describe('RandomTestComponent', () => {
  let component: RandomTestComponent;
  let fixture: ComponentFixture<RandomTestComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ RandomTestComponent, RandomTestChildComponent ],
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(RandomTestComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });  

  it('Testing if receiving input from one component to another works properly', () => {

    const childComp: RandomTestChildComponent = fixture.debugElement.query(By.directive(RandomTestChildComponent)).componentInstance;
    expect(childComp).toBeTruthy();
    expect(childComp.variableThatStoresTheDataThatTheChildReceives).toEqual('This is a test.');
  });

});

推荐阅读