【发布时间】: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