在Jest中模拟类常量

时间:2020-07-11 20:48:18

标签: javascript reactjs mocking jestjs enzyme

假设我有以下组件,可在构造函数中设置常量this.MAX_LENGTH

import PropTypes from 'prop-types';
import React from 'react';

class Input extends React.Component {
  static propTypes = {
    value: PropTypes.string.isRequired
  };

  constructor(props) {
    super(props);

    // An example constant
    this.MAX_LENGTH = 1024;
  }

  render() {
    
    return (
      <label htmlFor="comment_body">
        <textarea
          className="comment-reply input-highlight-on-focus"
          type="input"
          name="comment[body]"
          id="comment_body"
          maxLength={this.MAX_LENGTH}
          value={this.props.value} />
      </label>
    )
  }

}

export default Input;

MAX_LENGTH常量用于设置textarea的最大长度。

在我的Jest规格中,我想模拟this.MAX_LENGTH的值,但是我不确定如何设置该模拟。

这是我的Jest测试的外观(它使用chaienzyme作为测试助手):

it('renders the textarea', () => {
  // Mock the constant here to set a custom value of 99
  // ????

  const wrapper = mount(<Input value={'foo'} />)
  const textarea = wrapper.find('.comment-reply').first();

  expect(textarea).to.have.attr('maxLength', '99');
});

我可以用模拟值代替????吗?

我尝试通读Jest文档中的ES6 Class Mocks,但它似乎是在模拟整个导入的类,我不确定它将如何应用于单个常量。

谢谢!

1 个答案:

答案 0 :(得分:1)

对常量使用实例属性被认为是一种不好的做法。这就是静态属性的用途。在安装组件之前,可以将其模拟为Input.MAX_LENGTH = ...

class Input extends React.Component {
  static MAX_LENGTH = 1024;
  ...
}

原始值需要在afterEach中恢复。

或者至少使其成为只读原型属性。在安装组件之前,可以将其模拟为jest.spyOn(Input, 'MAX_LENGTH', 'get').mockReturnValue(...)

class Input extends React.Component {
  get MAX_LENGTH() { return 1024 };
  ...
}

否则,需要在初始渲染后在组件实例上对其进行模拟:

const wrapper = mount(<Input value={'foo'} />)
wrapper.instance().MAX_LENGTH = ...;
wrapper.setProps({});
...