【发布时间】: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 测试的样子(它使用 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');
});
我可以用模拟常量的值来替换???? 什么?
我尝试通读 Jest 文档中的 ES6 Class Mocks,但它似乎是在模拟整个导入的类,我不确定它如何应用于单个常量。
谢谢!
【问题讨论】:
-
你不能在不模拟整个事物的情况下模拟一个类。要么在
constructor中断言实际的硬编码值(我知道是脆弱的测试),要么将MAX_LENGTH值放在常量文件中并将其导入到类和测试文件中
标签: javascript reactjs mocking jestjs enzyme