javascript - 笑话/酶 | 测试屏蔽/取消屏蔽密码功能
问题描述
我在我的反应组件中有一个表单,它有 2 个调用函数的字段,单击时会show button
屏蔽和取消屏蔽特定字段。基本上,我需要一些关于如何测试函数本身的帮助。
功能:
togglePasswordMask = e => {
const { type } = this.state;
e.preventDefault();
this.setState(prevState => ({
passwordIsMasked: !prevState.passwordIsMasked,
type: type === 'password' ? 'input' : 'password'
}));
};
我在我的渲染方法中调用该函数,如下所示:
<div className="input-group mb-3">
<Field
type={type}
className={classNames('form-control', {
'is-invalid': errors.password && touched.password
})}
placeholder="Password (Required)"
name="password"
/>
<div className="input-group-append">
<span className="input-group-text">
<div
className={type === 'password' ?
'fa fa-eye fa-lg' : 'fa fa-eye-slash fa-lg'}
onClick={this.togglePasswordMask}
/>
</span>
</div>
</div>
它还有一个 INITIAL_STATE:
state = {
type: 'password',
groups: []
};
你能帮我吗,为此使用 Jest 和 Enzyme 编写测试用例。我尝试了以下方法,但它们似乎不起作用:
describe('UserCreateForm TogglePassword', () => {
it('Should unmask password and confirmPassword on click', () => {
const maskElement = wrapper.find('.fa fa-eye fa-lg');
const maskFn = maskElement.simulate('click');
expect(maskFn().state()).toEqual('input');
});
});
我得到这个错误:TypeError: Cannot read property 'preventDefault' of undefined
。
在找到另一个答案后,我进行了一点迭代,现在我的测试看起来像这样:
it('Should unmask password and confirmPassword on click', () => {
console.log(wrapper.debug());
const maskElement = wrapper.find('.fa-eye');
const maskFn = maskElement.simulate('click', {
preventDefault: () => {}
});
expect(maskFn().state()).toEqual('input');
});
现在,我得到另一个错误:maskFn, is not a function
.
解决方案
您的直接问题是因为根据Enzyme docsmaskElement.simulate
返回,这是一个对象而不是函数。完全摆脱,调用并忽略它的返回值,然后运行你的反对。Self
maskFn
maskElement.simulate
expect
maskElement.state()
(另外,不要针对组件的内部状态进行测试——有些人认为这是一种反模式,因为你正在测试组件实现而不是组件行为——考虑expect
让组件呈现 a <Field type="password" />
vs a <Field type="text" />
)
推荐阅读
- selenium - 从渲染器接收消息超时:0.100 条使用 ChromeDriver 和 Chrome v80 通过 Selenium Java 的日志消息
- java - NotifyService.Java 类根本没有被调用
- php - Wordpress PHP 警告:非法字符串偏移 'plugin_name'
- scala - 播放 JSON 库和 sbt 程序集合并错误
- javascript - Object.assign 替代 getter/setter
- rest - RESTful API 和统计页面
- powershell - 如何在powershell脚本中添加凭据,这样当我运行脚本时它不会要求输入密码,我不希望在脚本中看到密码
- angular - 如何使用xlsx Angular 8在下载的excel中显示选定的列
- unit-testing - react-navigation-hooks:如何测试 useFocusEffect
- php - 将 header('location: ..\') 设为页面上的当前滚动点