Skip to content

No way to test components relying on global styles #11072

Closed
@jnizet

Description

@jnizet

Versions

Angular CLI: 6.0.5
Node: 8.11.1
OS: darwin x64
Angular: 6.0.3
... common, compiler, compiler-cli, core, forms
... language-service, platform-browser, platform-browser-dynamic
... router

Package                           Version
-----------------------------------------------------------
@angular-devkit/architect         0.6.5
@angular-devkit/build-angular     0.6.5
@angular-devkit/build-optimizer   0.6.5
@angular-devkit/core              0.6.5
@angular-devkit/schematics        0.6.5
@angular/cli                      6.0.5
@ngtools/webpack                  6.0.5
@schematics/angular               0.6.5
@schematics/update                0.6.5
rxjs                              6.2.0
typescript                        2.7.2
webpack                           4.8.3

Repro steps

  • Create a new project
  • Edit src/styles.css and add the following rule:
.foo {
    display: none;
}
  • Add the following to src/app/app.component.html:
  <div class="foo">should not be displayed</div>
  • Add the following test to src/app/app.component.spec.ts:
  it('should not display hidden text', () => {
    const fixture = TestBed.createComponent(AppComponent);
    fixture.detectChanges();
    expect(fixture.nativeElement.innerText).not.toContain('should not be displayed');
  });
  • Run ng test

Observed behavior

The test fails

Desired behavior

The test passes

Mention any other details that might be useful (optional)

To be honest, I'm not quite sure if it's a bug or a feature. The test fails because the generated styles bundle is not served and included in the karma test frame as it is when using ng serve. The behavior of the component is thus not the same during tests as it is when used in production.

The above shows a simple case, where I could just check that the div element has the appropriate class. But I've had a case where, for example, a div containing an error message had to have a given CSS class and be a sibling of another specific div to have its messages displayed or hidden correctly. A simple test checking that the error message is displayed or not based on the state of the component is not doable in such a case, due to the absence of the global styles, which is a pain.
Is there a way to apply the global styles in tests?

Is it a conscious choice not to apply the styles in tests, or is it a bug?

I tried to get help from stackoverflow before submitting the issue, but without any luck.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions