Teat:用情感“CSS”测试图书馆(emotion teat)

关于Teat的问题,在emotion teat中经常遇到, 你好,我有两个问题与 Next.js,测试库 / 反应和情感。

你好,我有两个问题与 Next.js,测试库 / 反应和情感。

问之前,我会告诉你的代码

// 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');
});

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

enter image description here

第二个问题。测试失败,没有 css 道具的风格

enter image description here

如何处理此警告和错误?

我将发布 babelrc,jest.config 和设置

// 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'],
};
1

第一个问题

这是与将函数(theme) => css``(theme) => css({})传递到 css prop 相关的问题。

你可以用useThemehook解决这个问题。

import {css, Theme, useTheme} from '@emotion/react';
function Foo() {
  const theme: Theme = useTheme()
  return (
    <h1 css={css`color: ${theme.colors.primary}`}>
      title
    </h1>
  )
}

第二个问题

您需要使用@emotion/jest中的custom matchers

import {matchers} from '@emotion/jest'
expect.extend(matchers)
it('position absolute', () => {
  render(<Foo />);
  expect(screen.getByRole('heading')).toHaveStyleRule('position', 'absolute');
});

注意:为了使这项工作,不要忘记使用 css prop 在组件中添加 pragma/** @jsxImportSource @emotion/react */

本站系公益性非盈利分享网址,本文来自用户投稿,不代表码文网立场,如若转载,请注明出处

(946)
好听又有趣的cp名:有趣的字谜(fun anagrams)
上一篇
Python是什么类型的语言:JavaScript是什么类型的语言
下一篇

相关推荐

发表评论

登录 后才能评论

评论列表(13条)