样式化组件/宏不适用于Jest

cvxl0en2  于 2023-03-16  发布在  Jest
关注(0)|答案(1)|浏览(156)

我试图将Jest(ts-jest)集成到我的使用styled-components/macros的 typescript 项目中。但是由于某种原因,Jest报告了以下错误:

ts-jest[versions] (WARN) Version 4.0.2 of typescript installed has not been tested with ts-jest. If you're experiencing issues, consider using a supported version (>=4.3.0 <5.0.0-0). Please do not report issues in ts-jest if you are using unsupported versions.
 FAIL  packages/xx/src/components/button.test.tsx
  ● Test suite failed to run

    TypeError: macro_1.default.button is not a function

      2 |
      3 | export const Context = {
    > 4 |   Root: styled.button``,
        |                      ^
      5 | }
      6 |

      at Object.<anonymous> (packages/xx/src/components/button.mock.tsx:4:22)
      at Object.<anonymous> (packages/xx/src/components/button.test.tsx:5:1)

Test Suites: 1 failed, 1 total
Tests:       0 total
Snapshots:   0 total
Time:        7.073 s
Ran all test suites.
error Command failed with exit code 1.

TsConfig

const path = require("path");
const { lstatSync, readdirSync } = require("fs");

// get listing of packages in mono repo
const basePath = path.resolve(__dirname, "packages");
const packages = readdirSync(basePath).filter((name) =>
  lstatSync(path.join(basePath, name)).isDirectory()
);

/** @type {import('ts-jest').InitialOptionsTsJest} */
module.exports = {
  preset: "ts-jest",
  testEnvironment: "node",

  rootDir: ".",
  setupFiles: [],
  moduleDirectories: [
    'node_modules',
    '<rootDir>'
  ],
  transformIgnorePatterns: ['<rootDir>/node_modules/'],
  moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json'],
  setupFilesAfterEnv: [
    '<rootDir>/setupTests.ts', 
    '<rootDir>/shimTests.ts',
    '@testing-library/jest-dom/extend-expect'
  ],
  testMatch: ['**/*.test.(ts|tsx|js)'],

  moduleNameMapper: {
    "^.+\\.(css|less|scss)$": "babel-jest",
    // automatically generated list of our packages from packages directory.
    // will tell jest where to find source code for @ahoopen/ packages, it points to the src instead of dist.
    ...packages.reduce(
      (acc, name) => ({
        ...acc,
        [`@ahoopen/${name}(.*)$`]: `<rootDir>/packages/./${name}/src/$1`,
      }),
      {}
    ),
  },
  modulePathIgnorePatterns: [
    ...packages.reduce(
      (acc, name) => [...acc, `<rootDir>/packages/${name}/dist`],
      []
    ),
  ],

  globals: {
    'ts-jest': {
      // ts-jest configuration goes here and your IDE will suggest which configs when typing
      babelConfig: {
        "presets": [
          [
            "@babel/preset-env",
            {
              "targets": {
                "node": "10"
              }
            }
          ]
        ],
        // presets: ['@babel/preset-env', '@babel/preset-typescript', '@babel/preset-react'],
        plugins: ['macros'],
      }
    },
  },
};

开发依赖项

"devDependencies": {
    "@babel/cli": "^7.17.10",
    "@babel/core": "^7.18.0",
    "@babel/plugin-transform-runtime": "^7.18.0",
    "@babel/preset-env": "^7.18.0",
    "@babel/preset-react": "^7.17.12",
    "@babel/preset-typescript": "^7.17.12",
    "@testing-library/jest-dom": "5.16.4",
    "@testing-library/react": "13.2.0",
    "@types/jest": "27.5.1",
    "@types/node": "17.0.35",
    "babel-plugin-macros": "^3.1.0",
    "babel-plugin-styled-components": "^2.0.7",
    "enzyme": "3.11.0",
    "enzyme-adapter-react-16": "1.15.6",
    "eslint": "7.7.0",
    "is-ci": "2.0.0",
    "jest": "28.1.0",
    "jest-image-snapshot": "4.5.1",
    "jest-styled-components": "7.0.8",
    "jsdom-screenshot": "4.0.0",
    "lerna": "3.22.1",
    "react-dom": "18.1.0",
    "rimraf": "3.0.2",
    "styled-components": "5.3.5",
    "ts-jest": "28.0.2",
    "typescript": "4.0.2"
  }
``
db2dz4w8

db2dz4w81#

我是新的笑话和风格的组件。我遇到了一个类似的错误,如上所述。我希望有人有一个解决方案。
●测试套件运行失败

TypeError: macro_1.default.h2 is not a function

   8 | }
   9 |
> 10 | export const ViewHeader = styled.h2<HeaderProp>`
     |                                  ^
  11 |   color: ${({ titleColor }) => titleColor};
  12 |   font-family: Fjalla One, sans-serif;
  13 |   text-align: center;

我的测试

import React from "react";
import { renderHook, waitFor } from "@testing-library/react";
import { QueryClient,  QueryClientProvider,  useQuery,} from "@tanstack/react-query";
import BlogFAQ from "../../../src/views/OCVBlogFAQ/OCVBlogFAQ";
export function useCustomHook() { return useQuery({ queryKey: ["customHook"], queryFn: () => "Hello" }); 
}
describe("Blog FAQ", function () { it("should return blog posts", async function () {
   const queryClient = new QueryClient();
   const wrapper = () => (
  <QueryClientProvider client={queryClient}>
    <BlogFAQ
      viewData={{}}
      link={{}}
      anchorID={{}}
      showSearch={{}}
    />
  </QueryClientProvider>
);
const { result } = renderHook(() => useCustomHook(), { wrapper });
await waitFor(() => expect(result.current.isSuccess).toBe(true)); }); });

测试失败的样式

export const ViewHeader = styled.h2<HeaderProp>`
  color: ${({ titleColor }) => titleColor};
  font-family: Fjalla One, sans-serif;
  text-align: center;
  text-transform: uppercase;
  margin: 0;
  font-size: 2.25rem;
  @media (max-width: 768px) {
    font-size: 1.5rem;
  }
  `;

我没有意识到我正在尝试执行的测试需要很多关于jest测试的知识。我希望有人能给我指出一个解决方案,文档,视频和/或培训。

相关问题