Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 开玩笑地模仿类常量_Javascript_Reactjs_Mocking_Jestjs_Enzyme - Fatal编程技术网

Javascript 开玩笑地模仿类常量

Javascript 开玩笑地模仿类常量,javascript,reactjs,mocking,jestjs,enzyme,Javascript,Reactjs,Mocking,Jestjs,Enzyme,假设我有下面的组件,它在构造函数中设置了一个常量,this.MAX\u LENGTH import PropTypes from 'prop-types'; import React from 'react'; class Input extends React.Component { static propTypes = { value: PropTypes.string.isRequired }; constructor(props) { super(prop

假设我有下面的组件,它在构造函数中设置了一个常量,
this.MAX\u 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;

我可以用常量的模拟值替换

我试着通读Jest文档,但它似乎是在模仿整个导入的类,我不确定它将如何应用于单个常量


谢谢

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

class Input extends React.Component {
  static MAX_LENGTH = 1024;
  ...
}
class Input extends React.Component {
  get MAX_LENGTH() { return 1024 };
  ...
}
每次之后,需要在
中恢复原始值

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

class Input extends React.Component {
  static MAX_LENGTH = 1024;
  ...
}
class Input extends React.Component {
  get MAX_LENGTH() { return 1024 };
  ...
}
否则,需要在初始渲染后对组件实例进行模拟:

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

如果不模拟整个对象,就无法模拟一个类。要么在
构造函数
中断言实际的硬编码值(脆性测试,我知道),要么将
MAX_LENGTH
值放入常量文件中,并将其导入类和测试文件中