React 测试库不渲染 Emotion CSS

Ale*_*lex 7 emotion reactjs react-testing-library

运行 React 测试库以在使用 Emotion css 属性的 JSX 上生成快照,导致没有渲染任何 CSS。

我试过使用“@emotion/jest/serializer”,但仍然没有运气。

成分:

<button
      role="button"
      css={(theme)=> {
        backgroundColor: 'hotpink',
        '&:hover': {
          color: theme('lightgreen'),
        },
      }}
/>
Run Code Online (Sandbox Code Playgroud)

测试:

import React from 'react';
import { render } from '@testing-library/react';
import { createSerializer } from '@emotion/jest';

import { Component } from './component';

expect.addSnapshotSerializer(createSerializer());

describe('IconComponent', () => {
  it('should match the snapshot for the given props', () => {
    const { asFragment } = render(<Component icon="knownIcon" />);
    
    expect(asFragment()).toMatchSnapshot();
  });
Run Code Online (Sandbox Code Playgroud)

快照:( 这被呈现为匿名对象而不是 CSS)

exports[` 1`] = `
<DocumentFragment>
  <button
    css="[object Object]"
    role="button"
  />
</DocumentFragment>
`;
Run Code Online (Sandbox Code Playgroud)

Mic*_*ung 2

我认为你只是错过了最后一步。

https://emotion.sh/docs/css-prop

在使用 css 属性的源文件顶部设置 jsx pragma。此选项最适合测试 css prop 功能......例如 Create React App 4 然后 /** @jsx jsx / pragma 可能不起作用,你应该使用 / * @jsxImportSource @emotion/react */ 代替。

根据情感文档,/* @jsxImportSource @emotion/react */在组件文件顶部添加有助于css在测试中渲染的选项。

自定义按钮.js

/** @jsxImportSource @emotion/react */

export function CustomButton() {
  return (
    <button
      css={{
        "backgroundColor": "hotpink",
        "&:hover": {
          color: "lightgreen"
        }
      }}
    ></button>
  );
}
Run Code Online (Sandbox Code Playgroud)

结果

exports[`IconComponent should match the snapshot for the given props 1`] = `
<DocumentFragment>
  .emotion-0 {
  background-color: hotpink;
}

.emotion-0:hover {
  color: lightgreen;
}

<button
    class="emotion-0"
  />
</DocumentFragment>
`;
Run Code Online (Sandbox Code Playgroud)

如果您不使用 create-react-app,请改用以下命令:

/** @jsx jsx */
import { jsx } from '@emotion/react'
Run Code Online (Sandbox Code Playgroud)

这是存储库,您可以克隆它来测试它。


旧版本

对于旧版本的 React (< 16.4),您将需要使用 back"@emotion/core"而不是以"@emotion/react"旧方式转译文件。

包.json

 "@emotion/core": "10.1.1",
Run Code Online (Sandbox Code Playgroud)

按钮.js

/** @jsx jsx */
import { jsx } from '@emotion/core' <--- use the @emotion/core to transpile the file in old way. 

import React from "react";

const Button = () => {
  return (
    <button
      css={{
        backgroundColor: "hotpink",
        "&:hover": {
          color: "lightgreen"
        }
      }}
    ></button>
  );
};

export default Button;
Run Code Online (Sandbox Code Playgroud)

这是演示的存储库