【问题标题】:Mocking a class constant in Jest在 Jest 中模拟类常量
【发布时间】:2020-11-01 09:12:55
【问题描述】:

假设我有下面的组件,它在构造函数中设置了一个常量 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,但它似乎是在模拟整个导入的类,我不确定它如何应用于单个常量。

谢谢!

【问题讨论】:

  • 你不能在不模拟整个事物的情况下模拟一个类。要么在 constructor 中断言实际的硬编码值(我知道是脆弱的测试),要么将 MAX_LENGTH 值放在常量文件中并将其导入到类和测试文件中

标签: javascript reactjs mocking jestjs enzyme


【解决方案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({});
...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-09-14
    • 1970-01-01
    • 2017-03-19
    • 2021-04-19
    • 2021-12-21
    • 1970-01-01
    • 1970-01-01
    • 2021-12-08
    相关资源
    最近更新 更多