简体   繁体   English

Glimmer 中的组件单元测试

[英]component unit testing in Glimmer

For classic component unit tests, how would we migrate this to Glimmer?对于经典的组件单元测试,我们如何将其迁移到 Glimmer? This component unit test is testing a local prop that is not exposed to the user.此组件单元测试正在测试未向用户公开的本地道具。

const component = this.owner
  .factoryFor('component:some-component')
  .create({
    someModel: { foo: 'bar' }
  });

assert.equal(component.get('someLocalProp'), false);

These are indeed an anti-pattern, Indeed: unit testing components is an anti-pattern in general: you're not actually testing the interface of the component that way.这些确实是一种反模式,确实:单元测试组件通常是一种反模式:您实际上并没有以这种方式测试组件的接口 Here's what I mean by that: all interactions with the component, both as another developer invoking it and as a user interacting with it, happen via the template.这就是我的意思:与组件的所有交互,无论是作为另一个开发人员调用它还是作为用户与之交互,都是通过模板发生的。 "Unit" testing it like this does not represent how either the end user or the other developers who invoke it will be able to interact with it.像这样对它进行“单元”测试并不代表最终用户调用它的其他开发人员将如何与之交互。

Most of the time, tests like this exist because a developer wanted to check the behavior of an internal method or getter.大多数时候,存在这样的测试是因为开发人员想要检查内部方法或 getter 的行为。 However, that's exactly the opposite of what we should do when testing.然而,这与我们在测试时应该做的完全相反 We only want to test the public contract: that's what allows us to actually do the work of refactoring: that is, changing the internal implementation without changing the public contract.我们只想测试公共合约:这就是让我们能够实际进行重构工作的原因:即在更改公共合约的情况下更改内部实现。 Tests which rely on internal behavior are necessarily over-coupled and fragile.依赖于内部行为的测试必然是过度耦合和脆弱的。 In the case of UI components, that means that "unit" tests like this are effectively always over-coupled and fragile.对于 UI 组件,这意味着像这样的“单元”测试实际上总是过度耦合且脆弱。

For example, if a getter isn't visible in the template directly, who cares whether it computes a given value or not?例如,如果 getter 在模板中不直接可见,谁在乎它是否计算给定值? We really only care about the result of the computation.我们真的只关心计算的结果

There's no directly-corresponding API for Glimmer components, partly for that reason. Glimmer 组件没有直接对应的 API,部分原因是这个原因。 The right pattern here is to rewrite the component test into an integration test, which does allow you to test the actual interface of the component (or to remove it if it's not providing actual value).这里正确的模式是将组件测试重写为集成测试,这确实允许您测试组件的实际接口(或者如果它没有提供实际值,则将其删除)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM