Problems with Angular's NO_ERRORS_SCHEMA?

2020-06-03 06:51发布

问题:

When testing a component that has sub-components you have a few options:

  1. Import the module that sets up the component and sub-components. Problem is you instantiate the real sub-components and their dependencies.
  2. Mock sub-components. This can be tedious depending on how many sub-components it has.
  3. Use NO_ERRORS_SCHEMA and ignore sub-components.

Given that most of the time you only care about the current component, why isn't NO_ERRORS_SCHEMA given more attention in the testing tutorials, blog posts, etc.?

I know it's flagged as experimental but I'm not bothered by that since

  1. it's shipped with the rest of Angular, and
  2. the whole Angular stack is pretty much experimental given its history and the upcoming release cycle.

So are there problems with NO_ERRORS_SCHEMA? Or is it just happenstance it's not promoted more?

回答1:

I agree with @jonsharpe's assessment in that, you hide any template errors when you use NO_ERROR_SCHEMA, you will likely mask schema errors.

The alternative of importing the module with TestBed causes dependency-tree-hell.

There is a third alternative shallow-render that will mock your dependency tree automatically so you get type-safety, template safety and dependency-tree resolution with a single line of test setup.

Full-disclosure, I am the author of shallow-render.