【问题标题】:Testing Library with Emotion 'css'带有情感“css”的测试库
【发布时间】:2022-06-14 03:45:08
【问题描述】:

您好,我有两个关于 Next.js 的问题,testing-library/react 和emotion。

在问之前,我会在下面显示代码

// component
import { css, Theme } from '@emotion/react';

function Foo() {
  return <h1 css={fooCss}>title</h1
}

const fooCss = (theme: Theme) => css`position: absoulte;`;
// test code
it('position absoulte', () => {
  render(<Foo />);
  expect(screen.getByRole('heading')).toHaveStyle('position: absoulte');
});

第一个问题。开玩笑的警告:标签上 prop 'css' 的值无效...警告

第二个问题。测试失败,css prop 没有样式

我该如何处理这个警告和错误?

我将使用 babelrc、jest.config 和 setup 发布

// jest.config.js
const nextJest = require('next/jest');

const createJestConfig = nextJest({
  dir: './',
});

const customJestConfig = {
  resetMocks: true,
  moduleDirectories: ['node_modules'],
  testEnvironment: 'jsdom',
  testRegex: '(/__tests__/.*|(\\.|/)(test))\\.[jt]sx?$',
  collectCoverageFrom: ['**/src/**/*.{js,ts,jsx,tsx}'],
  moduleNameMapper: {
    '~/(.*)': '<rootDir>/src/$1',
    '.+\\.(css|styl|less|sass|scss|png|jpg|ttf|woff|woff2|ico)$': 'identity-obj-proxy',
  },
  moduleFileExtensions: ['js', 'jsx', 'json', 'ts', 'tsx'],
  transform: {
    '^.+\\.tsx?$': 'esbuild-jest',
  },
  coverageThreshold: null,
  setupFilesAfterEnv: ['./jest.setup.js'],
};

module.exports = createJestConfig(customJestConfig);
// jest.setup.js
import '@testing-library/jest-dom';

window.matchMedia = query => ({
  matches: false,
  media: query,
  onchange: null,
  addListener: jest.fn(), // deprecated
  removeListener: jest.fn(), // deprecated
  addEventListener: jest.fn(),
  removeEventListener: jest.fn(),
  dispatchEvent: jest.fn(),
});
// .babelrc.js
module.exports = {
  presets: [
    [
      'next/babel',
      {
        'preset-react': {
          runtime: 'automatic',
          importSource: '@emotion/react',
        },
      },
    ],
  ],
  plugins: ['@emotion/babel-plugin'],
};

【问题讨论】:

  • 在你的组件代码中,不应该是css={fooCss()}吗?
  • @juliomalves 这对我不起作用:C

标签: reactjs jestjs next.js react-testing-library emotion


【解决方案1】:

第一个问题

这是一个与将函数 (theme) =&gt; css``(theme) =&gt; css({}) 传递给 css prop 有关的问题。

你可以用useTheme钩子解决这个问题。

import { css, Theme, useTheme } from '@emotion/react';

function Foo() {
  const theme: Theme = useTheme()
  return (
    <h1 css={css`color: ${theme.colors.primary}`}>
      title
    </h1>
  )
}

第二个问题

您需要使用来自@emotion/jestcustom matchers

/** @jsxImportSource @emotion/react */
// other imports ...
import {matchers} from '@emotion/jest'

expect.extend(matchers)

it('position absolute', () => {
  render(<Foo />);
  expect(screen.getByRole('heading')).toHaveStyleRule('position', 'absolute');
});

【讨论】:

    猜你喜欢
    • 2021-06-19
    • 2022-08-08
    • 2016-02-05
    • 2021-01-28
    • 2020-08-27
    • 2021-12-06
    • 1970-01-01
    • 1970-01-01
    • 2022-12-31
    相关资源
    最近更新 更多