[英]React testing structure using Enzyme
I have a react component that I want to test the structure.我有一个要测试结构的反应组件。
So when I run wrapper.debug()
it shows me an output like this.因此,当我运行
wrapper.debug()
它会向我显示这样的输出。
<Fragment>
<div className="SignupLoginContainer">
<div className="SignupLoginContainer__SliderBtnContainer">
<LoginSignupSliderButton toShow={[Function: toShow]} />
</div>
<div className="SignupLoginContainer__Form_Container">
<Login isLoggingInOrSigningUp={true} />
</div>
</div>
</Fragment>
Then I'm testing it like:然后我像这样测试它:
expect(wrapper.matchesElement(
<Fragment>
<div className="SignupLoginContainer">
<div className="SignupLoginContainer__SliderBtnContainer">
<LoginSignupSliderButton toShow={() => true} />
</div>
<div className="SignupLoginContainer__Form_Container">
<Login isLoggingInOrSigningUp={true} />
</div>
</div>
</Fragment>
)).toBeTrue()
Here's my component render method:这是我的组件渲染方法:
render() {
return (
<Fragment>
<div className={styles.SignupLoginContainer}>
<div className={styles.SignupLoginContainer__SliderBtnContainer}>
<LoginSignupSliderButton toShow={(val: boolean) => this.toLogInOrSignUp(val)} />
</div>
<div className={styles.SignupLoginContainer__Form_Container}>
<Login isLoggingInOrSigningUp={this.state.toLoginOrSignup} />
</div>
</div>
</Fragment>
);
}
}
My test works if I remove <LoginSignupSliderButton toShow={(val: boolean) => this.toLogInOrSignUp(val)} />
from the component and test.如果我从组件和测试中删除
<LoginSignupSliderButton toShow={(val: boolean) => this.toLogInOrSignUp(val)} />
的测试工作。
I'm suspecting because of the callback?我怀疑是因为回调?
What you need is snapshot testing
like so:您需要的是像这样的
snapshot testing
:
// yourcomp.test.js
import YourComp from './wherever-it-lives';
it('renders correctly', () => {
const wrapper = shallow(<YourComp/>);
expect(wrapper).toMatchSnapshot();
});
After this test passes, it will create a __snapshots__
folder in your project directory with the correct snapshot for your components markup.此测试通过后,它将在您的项目目录中创建一个
__snapshots__
文件夹,其中包含组件标记的正确快照。
NOTE: If you ever update your markup (HTML) again, this test will fail until you update your snapshot like so:注意:如果您再次更新标记 (HTML),此测试将失败,直到您像这样更新快照:
jest --updateSnapshot
And your test should be passing again.你的测试应该会再次通过。
PS.附注。 I have of course made an assumption you are using jest as your test runner.
我当然假设您使用 jest 作为测试运行程序。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.