Cannot check expect(elm).not.toBeVisible() for semantic-ui react component

前端 未结 1 461
盖世英雄少女心
盖世英雄少女心 2021-01-20 00:29

I\'m trying to test a react component and use expect(elm).not.toBeVisible() without success.

Update 3

I have cut down the code

相关标签:
1条回答
  • 2021-01-20 01:26

    Here is the answer according to the author of react-testing-library himself:

    Probably a JSDOM limitation (in codesandbox it runs in the real browser). Actually, the problem is that the css isn't actually loaded into the document in JSDOM. If it were, then that would work. If you can come up with a custom jest transform that could insert the css file into the document during tests, then you'd be set.

    So this would work if you were using CSS-in-JS.

    So basically the import './TestItem.css' part in the test will not works because JSDOM doesn't load it, therefore jest-dom could not understand the class shouldHide means display: none.

    Update:

    According to this Stack Overflow thread, you can insert css into jsdom:

    import React from 'react'
    import { render } from 'react-testing-library'
    import TestItem from '../TestItem'
    
    import fs from 'fs'
    import path from 'path'
    
    test.only('TestItem should render correctly', async () => {
      const cssFile = fs.readFileSync(
        path.resolve(__dirname, '../TestItem.css'),
        'utf8'
      )
      const { container, getByText, debug } = render(<TestItem hide={true} />)
    
      const style = document.createElement('style')
      style.type = 'text/css'
      style.innerHTML = cssFile
      container.append(style)
    
      const itemNode = getByText('Text')
      debug()
      expect(itemNode).not.toBeVisible()
    })
    

    And then the test should pass.

    0 讨论(0)
提交回复
热议问题