[英]Mocking a class constant in Jest
Say I have the below component that sets a constant, this.MAX_LENGTH
in the constructor.假设我有以下组件,它在构造函数中设置了一个常量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;
The MAX_LENGTH
constant is used to set the max length of the textarea
. MAX_LENGTH
常量用于设置textarea
的最大长度。
In my Jest specs I want to mock the value of this.MAX_LENGTH
, but I'm not sure how to set that mock.在我的 Jest 规范中,我想模拟this.MAX_LENGTH
的值,但我不确定如何设置该模拟。
Here's how my Jest test looks (it uses chai
and enzyme
as testing helpers):这是我的 Jest 测试的样子(它使用chai
和enzyme
作为测试助手):
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');
});
What can I replace ????
可以换什么????
with mock the value of the constant?用模拟常量的值?
I tried reading through ES6 Class Mocks in the Jest docs but it seemed to be around mocking a whole imported class and I'm not sure how it would apply to a single constant.我尝试在 Jest 文档中通读ES6 Class Mocks ,但它似乎在 mocking 左右,整个导入的 class 并且我不确定它如何应用于单个常量。
Thanks!谢谢!
Using instance properties for constants is considered a bad practice;对常量使用实例属性被认为是一种不好的做法; this is what static properties are for.这就是 static 属性的用途。 This would be possible to mock as Input.MAX_LENGTH =...
before mounting the component:这可以在安装组件之前模拟为Input.MAX_LENGTH =...
:
class Input extends React.Component {
static MAX_LENGTH = 1024;
...
}
Original value needs to be restored in afterEach
.原始值需要在afterEach
中恢复。
Or at least making it read-only prototype property.或者至少使它成为只读原型属性。 This would be possible to mock as jest.spyOn(Input, 'MAX_LENGTH', 'get').mockReturnValue(...)
before mounting the component:这可以在安装组件之前模拟为jest.spyOn(Input, 'MAX_LENGTH', 'get').mockReturnValue(...)
:
class Input extends React.Component {
get MAX_LENGTH() { return 1024 };
...
}
Without that, it needs to be mocked on component instance after initial render:没有它,它需要在初始渲染后在组件实例上进行模拟:
const wrapper = mount(<Input value={'foo'} />)
wrapper.instance().MAX_LENGTH = ...;
wrapper.setProps({});
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.