ダイナミックインポートを使用してモジュールをロードするMochaとEnzymeを使用してReactコンポーネントをテストしようとしています。ダイナミックインポート(React component with dynamic import)(Enzyme/Mocha)
動的インポートに依存するロジックをテストしようとすると、不正な結果が得られます。問題は、テストが終了する前に非同期関数が終了しないため、正確な結果を得ることができないということです。
このシナリオをどのように処理できますか?
コンポーネント
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
});
});
「ウェブパックの方法をスタブする」とはどういう意味ですか。あなたは動的なインポートを指していますか?もしそうなら、それはES6でwebpackに特有ではありません(ただし、chunkでwebpackはそれを別々に扱います)。また、インポートは特殊なキーワードであり、関数ではないので、私はあなたがそれをスタブできるとは思わない。 – anthonator
動的なインポートのためのES6の提案は、私がwebpack/babel/systemJSのようなツールで知っている限り実装されています。あなたが裸のES6で本当に何かを使っているなら、謝罪します。 実際のグローバル関数または実際のポリフィルではなく、単にツールからのものであれば、それを擬似することはできません – alechill