Skip to content

Unit test should fail if an element is not known #36430

Closed

Description

@sebastianhaeni

🚀 Unit test should fail if an element is not known

Relevant Package

This feature request is for @angular/core.
And I think this is a kinda a regression since this behavior changed with Ivy.

Description

When executing unit tests with Karma and my test module has not been setup correctly, to contain all the relevant components, I get a warning like this:

WARN: ''app-my-element' is not a known element:
1. If 'app-my-element' is an Angular component, then verify that it is part of this module.
2. If 'app-my-element' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.'

The test is still successful in that case. In my opinion it should fail, since the test module clearly is missing this component.

I saw that there have been efforts to make it appear as an error: 00f3c58.
This has been reverted in this commit: 00f3c58.

But that wouldn't change the fact, that the test still passes.

Describe the solution you'd like

I would like one of these options:

  • tests with unknown elements fail (as they did pre Ivy)
  • an option to enable this behavior to make the tests fail
    • i.e. a CLI argument or a property in angular.json

If the default is "fail", then a user could add CUSTOM_ELEMENTS_SCHEMA or NO_ERRORS_SCHEMA to their test module if they want to suppress the errors.

Activity

  1. changed the title [-]Unit test should have option to fail if an element is not known[/-] [+]Unit test should fail if an element is not known[/+] on Apr 4, 2020
  2. added
    area: core
    area: testing
    on Apr 5, 2020
  3. modified the milestone: needsTriage on Apr 5, 2020
  4. added
    regression
    on Apr 5, 2020
  5. modified the milestones: needsTriage, Backlog on Apr 5, 2020
  6. x87 commented on Apr 6, 2020

    @x87

    This is probably related to #36171

  7. danmana commented on Apr 9, 2020

    @danmana
    Contributor

    This has been driving me nuts for a few weeks.

    On my local machine, tests with unknown elements pass without even showing a warning.
    On the build server, the tests fail.

    Other types of failing tests behave the same on both machines (wrong expect statements fail on both)

    Test command: npm run test -- --watch false --progress false

    My machine:
    Windows 10 Pro, version 10.0.18363 Build 18363

    Angular CLI: 9.0.5
    Node: 12.16.0
    OS: win32 x64
    
    Angular: 9.0.5
    ... animations, cli, common, compiler, compiler-cli, core, forms
    ... language-service, platform-browser, platform-browser-dynamic
    ... router
    Ivy Workspace: Yes
    
    Package                           Version
    -----------------------------------------------------------
    @angular-devkit/architect         0.900.5
    @angular-devkit/build-angular     0.900.5
    @angular-devkit/build-optimizer   0.900.5
    @angular-devkit/build-webpack     0.900.5
    @angular-devkit/core              9.0.5
    @angular-devkit/schematics        9.0.5
    @angular/cdk                      9.1.1
    @angular/flex-layout              9.0.0-beta.29
    @angular/material                 9.1.1
    @ngtools/webpack                  9.0.5
    @schematics/angular               9.0.5
    @schematics/update                0.900.5
    rxjs                              6.5.4
    typescript                        3.7.5
    webpack                           4.41.2
    

    Build server:
    Gitlab-CI using image circleci/node:12-browsers

    I even tried running the tests locally in the same docker container that the build server uses, but to no avail, it still passes locally but fails once I push it to gitlab.

    Locally it's behaving like I have some global setting of schemas: [NO_ERRORS_SCHEMA] ...

  8. sebastianhaeni commented on Apr 22, 2020

    @sebastianhaeni
    ContributorAuthor

    In case anybody is interested, I have the following workaround in place until this is fixed:

    Executing the following function before creating the component with TestBed.createComponent() will ensure tests fail if there are unknown elements.

    Since we use a util function in every component test to setup our test bed, it was easy to add there.

    /**
     * Monkey patch console warn and error to fail if a test makes calls to console.warn or console.error.
     */
    function patchConsole(): void {
        console.warn = function(message?: any, ...optionalParams: any[]): void {
            const params = optionalParams ? `\nParams: ${optionalParams}` : '';
            fail(`Test contained console warning:\n${message}${params}`);
        };
        console.error = function(message?: any, ...optionalParams: any[]): void {
            const params = optionalParams ? `\nParams: ${optionalParams}` : '';
            fail(`Test contained console error:\n${message}${params}`);
        };
    }
  9. 20 remaining items

  10. distante commented on Sep 1, 2021

    @distante

    Monkey patching console.error does not work always. No idea why.

  11. gagle commented on Oct 5, 2021

    @gagle

    This is really an inconvenient. Having errors in console with unit tests passing is not good.

    I use this snippet:

    const originalConsoleError = window.console.error;
    
    const regExp = /^(NG0303|NG0304)/;
    
    console.error = (...args: unknown[]): void => {
      const message = args[0]?.toString();
      if (message?.match(regExp)) {
        const err = new Error(message);
        Error.captureStackTrace(err, console.error);
        throw err;
      }
    
      originalConsoleError(...args);
    };
    
    

    Stored in /setup-jest.ts and loaded from jest config using setupFiles property.

  12. KissBalazs commented on Oct 21, 2021

    @KissBalazs

    It would be nice if this feature could be a flag option to fail the test run upon any console.error. This way compatibility wouldn't be hurt.

  13. petebacondarwin commented on Oct 22, 2021

    @petebacondarwin
    Contributor

    We think that this could be changed to throw an error now, but it would be a breaking change that could land in 14.0.0 at the earliest. For now we will put it in the backlog, and run a test in Google to see how breaking it would be. If it turns out this is a big effort to merge into Google, when we will need to prioritize it as a project.

  14. kevinmerckx commented on Jan 4, 2022

    @kevinmerckx
    Contributor

    Isn't it a bug that is a breaking change introduced recently? Therefore, fixing this issue shouldn't be considered a breaking change, but rather a fixing change.

  15. added
    P4
    and removed
    P2
    on Feb 11, 2022
  16. cexbrayat commented on May 4, 2022

    @cexbrayat
    Member

    We landed two PRs that introduce new options for the TestBed in Angular v14 and that should fix this issue.

    You can now enable errorOnUnknownElements and/or errorOnUnknownProperties when setting up the TestBed globally or in a specific test to throw an error on unknown elements or unknown properties encountered in templates (instead of just logging the NG303/NG304 error).

    These new options are opt-in for now.

    If you're using the CLI, you can enable them globally in test.ts

    getTestBed().initTestEnvironment(
      BrowserDynamicTestingModule,
      platformBrowserDynamicTesting(),
      { 
        errorOnUnknownElements: true,
        errorOnUnknownProperties: true
      }
    );

    Or you can enable/disable them in a specific test:

    TestBed.configureTestingModule({
      declarations: [AppComponent],
      errorOnUnknownElements: true, 
      errorOnUnknownProperties: false
    })

    See https://next.angular.io/api/core/testing/TestModuleMetadata

  17. angular-automatic-lock-bot commented on Jun 4, 2022

    @angular-automatic-lock-bot

    This issue has been automatically locked due to inactivity.
    Please file a new issue if you are encountering a similar or related problem.

    Read more about our automatic conversation locking policy.

    This action has been performed automatically by a bot.

  18. locked and limited conversation to collaborators on Jun 4, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

P4area: corearea: testingcore: directive matchingfreq3: highregressionstate: confirmedtype: bug/fix

Type

No type

Projects

No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions