我正在尝试使用摩卡和酶来测试React组件,该组件使用动态导入来加载模块。使用动态导入测试React组件(酶/摩卡)
当我尝试测试依赖动态导入的逻辑时,我得到不正确的结果。问题是异步函数在测试完成之前没有完成,所以我永远无法得到准确的结果。
我该如何处理这种情况?
组件
import classNames from 'classnames';
import PropTypes from 'prop-types';
import React from 'react';
// styles
import styles from './PasswordStrengthIndicator.scss';
class PasswordStrengthIndicator extends React.Component {
static defaultProps = {
password: undefined,
onPasswordChange: undefined,
}
static propTypes = {
password: PropTypes.string,
onPasswordChange: PropTypes.func,
}
constructor() {
super();
this.state = {};
}
componentWillMount() {
this.handlePasswordChange();
}
componentWillReceiveProps(nextProps) {
const password = this.props.password;
const nextPassword = nextProps.password;
if (password !== nextPassword) {
this.handlePasswordChange();
}
}
render() {
const strength = this.state.strength || {};
const score = strength.score;
return (
<div className={ styles.passwordStrength }>
<div className={ classNames(styles.score, styles[`score-${score}`]) } />
<div className={ styles.separator25 } />
<div className={ styles.separator50 } />
<div className={ styles.separator75 } />
</div>
);
}
// private
async determineStrength() {
const { password } = this.props;
const zxcvbn = await import('zxcvbn');
let strength = {};
if (password) strength = zxcvbn(password);
return strength;
}
async handlePasswordChange() {
const { onPasswordChange } = this.props;
const strength = await this.determineStrength();
this.setState({ strength });
if (onPasswordChange) onPasswordChange(strength);
}
}
export default PasswordStrengthIndicator;
测试
describe('when `password` is bad',() => {
beforeEach(() => {
props.password = 'badpassword';
});
it.only('should display a score of 1',() => {
const score = indicator().find(`.${styles.score}`);
expect(score.props().className).to.include(styles.score1); // should pass
});
});
我不确定你的意思是“stubbing a webpack method”。你是指动态导入?如果是这样,这是ES6,而不是特定于webpack(尽管webpack在分块时处理它的方式不同)。此外,导入是一个特殊的关键字,而不是一个功能,所以我不认为你可以将它存根。 – anthonator
对于动态导入的ES6建议,仅在我知道的webpack/babel/systemJS等工具中实现,如果您使用的是在裸露的ES6中使用的东西,则表示道歉。 这正是我的意思,如果它只是从一个工具,而不是一个实际的全局函数或一个真正的polyfill,你将无法嘲笑它 – alechill