Angular 4 - 如何解析模板中的连字符变量以进行业力测试



我在使用 Karma 对我的 Angular 4 组件进行单元测试时遇到了一个问题。以下是我正在运行测试的命令:

tsc && karma start --browsers PhantomJS

我有如下所示的连字符变量,它与 HTML 模板绑定,我验证了绑定是否有效并且数据显示在页面上(在浏览器中(。

连字符变量 - 在组件 .ts 文件中

template-variable-key

但是在单元测试期间,我遇到了一个问题,因为它给出了以下错误:

TypeError: Cannot read property 'layout-permission-title-key' of undefined

我如何在 HTML 模板中定义

(1( 在带有表达式的模板中
<p>{{error['template-variable-key']}}</p>
(2( OR 在具有数据绑定的模板中使用innerHtml
<p [innerHtml]="error['template-variable-key']"></p> <!-- or -->
<p [innerHtml]="error?.template-variable-key"></p>

注意:由于在 Angular 以外的许多地方都使用相同的连字符变量,因此我无法将其更改为驼峰或其他内容。

(

1(和(2(都对我不起作用。

提前感谢您的回答:)

您可以尝试的另一件事是,在尝试使用错误属性的任何地方上都有一个 *ngIf="error">

<p *ngIf="error" [innerHtml]="error['template-variable-key']"></p>

绑定正在查找一个名为 error 的属性,该属性未定义,因此当它尝试访问模板变量键时,您会收到未定义的错误。

您需要在组件上模拟错误对象。

通常你的等级库文件有一个像这样的部分在你的等级库中有一个这样的部分

let component: YourComponentType;
let fixture: ComponentFixture<YourComponentType>;
beforeEach(async(() => {
  TestBed.configureTestingModule({
    declarations: [ YourComponentType ]
  })
  .compileComponents();
}));
beforeEach(() => {
  fixture = TestBed.createComponent(YourComponentType);
  component = fixture.componentInstance;
  fixture.detectChanges();
});

在每一个之前的第二个,你可以模拟错误对象

component = fixture.componentInstance;
component.error = { };
component.error['template-variable-key'] = 'Your test data';

或者在您的组件中,错误对象只有一个默认值

error = {};

最新更新