Jest.js 如何测试动态页面标题?

ttp71kqs  于 6个月前  发布在  Jest
关注(0)|答案(2)|浏览(67)

我使用react-helmet,并根据某些条件更改文档页面标题。
如何使用react-testing-library测试这种行为?
我尝试了一些东西,

const { debug } = render(<TitleChangingComponent title="Test" />, {
    container: document.head,
});
debug();

字符串
但它只是在调试输出中显示了一个空值。另外,我不能100%确定这是与react-testing-library还是jsdom(我使用Jest进行测试)有关。

bqucvtff

bqucvtff1#

在被问到这个问题后的几年里,我遇到了这个问题,但为了防止其他人遇到这个问题,我可以用下面的方式来做:

beforeEach(() => {
  document.title = ''
})

test('Component changes title', () => {
  render(<Title title="Example" />)
  expect(document.title).toEqual("Example")
})

字符串

nuypyhwy

nuypyhwy2#

我不会用react-testing-library来做这个。
我会在E2E测试中测试这一点,例如Cypress。

cy.title().should('eq', '<your-title>')

字符串
意见:
使用单元测试和副作用测试组件和纯逻辑,以及使用端到端测试测试用户交互,这是best practice

相关问题