我目前正在为 React 中的一个组件编写测试覆盖率,如果 prop newUser
为 true,该组件将向 HTML 中注入(inject)脚本标记。当我运行测试并且将 prop 作为 true 传递时,它无法将脚本标记附加到文档正文,因此它无法检查脚本 src。我的组件是
class AddScript extends Component {
render() {
const {
newUser,
async,
} = this.props;
const asyncAttribute = async ? true : undefined;
if (newUser) {
return
<script src="http://www.website.com" async={asyncAttribute}>
</script>;
}
return (
<div />
);
}
}
使用 Jest 和 Enzyme 进行的测试均失败
it('should append the script tag if newUser is true', () => {
const wrapper = shallow(<AddScript newUser={true} />);
expect(wrapper).toMatchSnapshot();
const script = document.body.getElementsByTagName('script')[0];
expect(script.src).toEqual('http://www.website.com');
});
带有错误消息
TypeError: Cannot read property 'src' of undefined
我相信测试无法访问 if 语句,但我不确定为什么会出现这种情况,因为它肯定会在渲染 jsx 之前检查该条件?
有什么指点吗?谢谢:)
仅供引用,尽管该组件很简单,但我现在将其作为类组件,因为稍后我可能会添加生命周期 Hook 。
最佳答案
浅渲染不会将输出附加到 DOM,您需要 mount如果您想查询 document.body
您的组件.
如果您只是想验证您的组件是否呈现 <script>...</script>
,您仍然可以使用浅渲染来完成此操作。您只需要查询包装器而不是 DOM
it('should append the script tag if newUser is true', () => {
const wrapper = shallow(<AddScript newUser={true} />);
expect(wrapper.html()).toEqual('<script script="http://www.website.com"></script>');
});
关于javascript - 类型错误 : Cannot read property 'src' of undefined when loading script in React Enzyme,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59112567/