0

当我使用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"
    ]
}
4

1 回答 1

0

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

也决定不使用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.jsshallow工作:

"snapshotSerializers": [
  "enzyme-to-json/serializer"
]
于 2018-11-17T13:17:14.413 回答