html - 用于测试 React 应用程序的 jest/enzyme 不提供页面标题,如何获取标题?

标签 html reactjs jestjs enzyme create-react-app

我已经使用 create-react-app 创建了一个 React 应用程序,它已经生成了一个 React 应用程序的准系统,非常好!我现在想更改页面的标题(在 index.html 中)然后进行测试。我正在使用 enzyme 来测试单个组件,这也很棒,但它只提供从组件生成的 html。如何测试页面/dom,特别是页面的标题?

it('renders App', () => {
  const wrapper = mount(<App />);
  const title = 'test'
  console.log(global.window.document.title)
  expect(wrapper.contains(title)).toEqual(true);
});

global.window.document.title 为空

最佳答案

  1. 您可以在 render()componentDidMount() 中将 component/App.js 中的标题设置为

    document.title = 'titlename'
    

    并在此处检查该标题 expect(global.window.document.title).toBe('titlename')。对我有用!

  2. 尝试使用 react-helmet。然后检查

    wrapper.find(Helmet).prop("title")).toEqual('titlename');
    

关于html - 用于测试 React 应用程序的 jest/enzyme 不提供页面标题,如何获取标题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48097366/

相关文章:

javascript - Jest : test Intl. DateTimeFormat

javascript - Jest 模拟第三方对象

react-native - 无效或意外的 token ,测试裸 react native 应用程序

html - CSS - 无法摆脱边距

javascript - 使文本字段根据窗口宽度适当调整大小

html - 如果子项溢出,如何强制 100% 宽度的表行使用滚动条?

javascript - 我如何在 ReactJS 中包含 `<img>`?

reactjs - 父功能组件中的子项不会因 Prop 更改而重新渲染

javascript - css 调整水平下拉菜单的大小

javascript - 如何计算摩纳哥差异编辑器中更改的行数?