【问题标题】:Invariant Violation: Element type is invalid (Jest + TSX + StyledComponents)不变违规:元素类型无效(Jest + TSX + Styled Components)
【发布时间】:2019-04-17 19:43:55
【问题描述】:

当我使用 styled-components 时,我一直在努力使用 Jest 运行测试。

我从 styled-components/jest 中获取了示例代码

import * as React from 'react'
import styled from 'styled-components'
import * as TestRenderer from 'react-test-renderer'
import 'jest-styled-components'

const Button = styled.button`
  color: red;
`

test('it works', () => {
  const tree = TestRenderer.create(<Button />).toJSON()
  expect(tree).toMatchSnapshot()
  expect(tree).toHaveStyleRule('color', 'red')
})

我总是出现以下错误:

 Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object.

测试文件是 .tsx。 Jest 配置如下:

module.exports = {
    "roots": [
        "<rootDir>/src"
    ],
    "transform": {
        "^.+\\.tsx?$": "ts-jest"
    },
    "testRegex": "(/__tests__/.*|(\\.|/)(test|spec))\\.tsx?$",
    "moduleFileExtensions": [
        "ts",
        "tsx",
        "js",
        "jsx",
        "json",
        "node"
    ]
}

【问题讨论】:

    标签: jestjs styled-components tsx


    【解决方案1】:

    嗯,最终我最终使用酶进行测试。没有真正解决这个问题,但设法使它工作。

    还决定不使用jest-styled-components,因为上一个版本本身就有一些问题。希望我以后能做到这一点。

    import * as React from 'react'
    import styled from 'styled-components'
    
    const Button = styled.button`
    color: red;
    `
    
    test('it works', () => {
    const tree = shallow(<Button />);
    expect(tree).toMatchSnapshot()
    })
    

    不用说,您必须更新您的 jest.config.js 才能使 shallow 正常工作:

    "snapshotSerializers": [
      "enzyme-to-json/serializer"
    ]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-12-28
      • 1970-01-01
      • 2020-07-02
      • 2018-07-19
      • 2016-08-31
      • 2023-03-04
      • 1970-01-01
      • 2019-06-07
      相关资源
      最近更新 更多