TypeError:在React Enzyme中加载脚本时无法读取未定义的属性'src'

问题描述 投票:0回答:2

我目前正在为React中的组件编写测试覆盖率,如果prop newUser为true,该组件将向HTML注入脚本标签。当我运行测试并且通过了prop作为true时,它无法将script标签附加到文档主体,因此无法检查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和酶的测试失败

  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之前检查该条件吗?

任何指针?谢谢:)

FYI尽管此组件非常简单,但我现在将其作为类组件,因为稍后可能会添加生命周期挂钩。

javascript reactjs jestjs enzyme
2个回答
3
投票

浅表渲染不会将输出附加到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>');
});

0
投票

尝试将脚本标签放在花括号中:

if (newUser) { return ( <script src="http://www.website.com" async={asyncAttribute}> </script>); }
© www.soinside.com 2019 - 2024. All rights reserved.