【问题标题】:Loading external css in Angular 2 and testing it在 Angular 2 中加载外部 css 并对其进行测试
【发布时间】:2016-11-04 21:24:11
【问题描述】:

我正在尝试创建一个对其进行测试的组件。该组件具有我要测试的外部 CSS。我认为我做的一切都是正确的,但我无法通过考试。这是我的代码: app.component.spec.ts

import { AppComponent } from "./app.component";
import { async, TestBed } from "@angular/core/testing";
import { By } from "@angular/platform-browser";

describe("App Component", function () {
    beforeEach(async(() => {
        TestBed.configureTestingModule({
            declarations: [AppComponent],
        }).compileComponents()
    }));
    it("should instantiate component", () => {
        let fixture = TestBed.createComponent(AppComponent);
        expect(fixture.componentInstance instanceof AppComponent).toBe(true);
    });
    it("should have expected <h1> text", () => {
        let fixture = TestBed.createComponent(AppComponent);
        fixture.detectChanges();

        let h1 = fixture.debugElement.query(By.css("h1"));

        expect(h1.nativeElement.innerText).toBe("hello world!");

        expect(h1.nativeElement.style.color).toBe("blue");
    });
});

app.component.ts:

import { Component } from "@angular/core";

@Component({
    moduleId: module.id,
    selector: "nebula-app",
    styleUrls: ["./app.component.css"],
    templateUrl: "./app.component.html",
})
export class AppComponent { }

app.component.html:

<h1>hello world!</h1>

app.component.css:

h1{
    color: blue;
}

只有最后一个期望会失败。它认为 h1.nativeElement.style.color 为空。似乎它没有以某种方式加载CSS。如果我将样式设置为 html 中的线条样式,则此测试将通过。但是将其作为外部 css 会失败。

我做错了什么?我假设 compileComponents 应该加载外部 CSS 并将其作为 nativeElement 的样式是错误的吗?

【问题讨论】:

  • 颜色和背景颜色不同
  • @jonrsharpe 我的例子不好。我会编辑它,但还是不行
  • 你能比“不工作”更具体吗
  • @jonrsharpe 最后一个期望会抛出一个错误,因为它认为 h1.nativeElement.style.color 为空。如果我将样式设置为内联样式,它将起作用,但是将其放在外部 css 文件中会导致并清空 nativelement.style
  • 一个错误,还是一个失败的期望?你能edit 提供这些信息吗?

标签: testing angular typescript karma-jasmine


【解决方案1】:

h1.nativeElement.style 仅包含在元素上显式设置的样式。例如,下面的元素会有一个样式对象,backgroundColorset 为 red

<h1 style="background-color: red;">hello world!</h1>

您可以使用量角器 e2e 测试来测试它,而不是对颜色使用单元测试。在那里你可以写一个这样的测试:

expect(element(by.css('h1')).getCssValue('color')).toEqual('rgba(0, 0, 255, 1)');

Protractor e2e 测试内置于 angular-cli 生成的 Angular2 项目中。您可以使用命令ng e2e 运行它们

【讨论】:

  • 原来如此。是的,我把它改成了量角器,它起作用了。但我有一个问题。这是为什么呢?
  • @user3521794 好问题。我不知道。也许他们是这样看的:应用程序的外观不属于单元测试,而是更自然地是整个应用程序集成测试的一部分,其中所有元素都显示并受到所有 css 表格的影响,包括全局表格。所以这就是他们在 e2e 中创建功能来测试 css 的原因。
【解决方案2】:

不确定这是否是一个好习惯,但可以测试计算样式。 不过,将您的最后一个 except 更改为类似的内容应该可以:

expect(window.getComputedStyle(h1.nativeElement).color).toBe('rgb(0, 0, 255)');

【讨论】:

  • +1 用于提供适用于组件测试范围的答案。虽然可以说这些类型的检查更适合 e2e 测试。有时,只需检查单个组件上的特定内容而无需启动整个 e2e 测试,这是很有价值的。
猜你喜欢
  • 2016-12-28
  • 2018-01-30
  • 2016-04-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-25
  • 1970-01-01
相关资源
最近更新 更多