【问题标题】:Any possible to way to ignore decorators only for tests?有什么方法可以忽略仅用于测试的装饰器?
【发布时间】:2018-05-17 05:19:09
【问题描述】:

我目前在为 reactjs 应用程序编写的单元测试中遇到装饰器问题。

我喜欢我们通过在我们的 react 组件中引入装饰器来避免如此多的样板代码的方式,组件看起来很干净,并且代码变得更具可读性。 但是现在对这些无意义的装饰器感到非常恼火,因为我无法运行单个单元测试,这是在我的应用程序上下文中必须测试的。代码描述如下:

@translate(['common'])
export default class MyComponent extends React.Component {
 ...
 componentDidMount() {
  // Ajax call on success setting the state this.setState({ myData: response.data })
 }
 ...
}

想测试这个组件的状态,我收到了来自 ajax 的成功响应。

我的测试如下所示

describe('<MyComponent />', function () {
 sinon.stub(dataService, 'fetchData')
  callsFake(function () {
   return Promise.resolve(['one', 'two', 'three'])
  });
 it('should match the state with data fetched', function () {
  const wrapper = mount(<MyComponent />);
  return dataService.fetchData()
   .then(function () {
    expect(wrapper.state('myData')).to.have.lengthOf(3);
   });
 });
});

如果我从组件中删除 @translate(['common']),上述测试效果很好,但如果存在则不起作用。 我知道 translate 是一个 HOC,我需要相应地调整我的测试,但相信我,我尝试了一切,对我没有任何作用。 还有一种方法可以通过在组件中添加多个导出来实现这一点,一个是纯的,另一个是用翻译包装的,但是对于这个解决方案,我还必须删除我喜欢在我的源代码中包含的装饰器。

那么有什么方法可以配置我们的 webpack 在运行测试期间忽略或跳过我的源代码中的这些装饰器?

【问题讨论】:

  • 装饰器不是 ES7 的一部分。

标签: webpack decorator ecmascript-next


【解决方案1】:

因为装饰器只是Higher-Order Functions 的糖,你可以将类声明和类的装饰分开,但是你失去了漂亮的@ 装饰语法,因为you can only use decorators on an export when exporting a class

export class MyComponent extends React.Component {
 ...
 componentDidMount() {
  // Ajax call on success setting the state this.setState({ myData: response.data })
 }
 ...
}

export default translate(['common'])(MyComponent)

在您的测试中,您现在可以导入底层的“未修饰”类:

import {MyComponent} from '...'

那么有什么方法可以配置我们的 webpack 在运行测试期间忽略或跳过我的源代码中的这些装饰器?

我不相信有任何方法可以让 webpack 忽略类的装饰。 有可能创建一些插件来解析文件并删除装饰语句,但这太过分了,并且会对应用程序开发和构建过程的其他部分产生无数影响。

【讨论】:

    猜你喜欢
    • 2014-02-17
    • 1970-01-01
    • 2012-03-14
    • 2015-08-11
    • 1970-01-01
    • 2016-12-16
    • 2018-06-05
    • 1970-01-01
    • 2023-03-17
    相关资源
    最近更新 更多