我创建了一个下一个函数组件,它基本上使用创建标签值负载中的值映射到一个 json 文件,如下所示。
import FooterCerts from "constants/json/FooterCerts.json";
import { NextFunctionComponent } from "next";
import * as React from "react";
import styles from "./index.scss";
export const FooterLogos: NextFunctionComponent = () => (
<React.Fragment>
<style jsx={styles.toString()}>{styles}</style>
<ul>
{FooterCerts.map((logo) => (
<a
href={logo.HREF}
title={logo.TITLE}
rel="noopener external"
target="_blank"
data-qa={logo.DATA_QA}
key={logo.KEY}
>
<li>
<img src={logo.FILE_PATH} alt={logo.ALT} />
</li>
</a>
))}
</ul>
</React.Fragment>
);
我的问题是在为这个组件创建单元测试时出现的。这是一个试图创建快照的基本测试。
import * as React from "react";
import { cleanup, render } from "react-testing-library";
import { FooterLogos } from ".";
afterEach(cleanup);
it("renders as expected", () => {
const { container } = render(<FooterLogos />);
expect(container).toMatchSnapshot();
});
这在运行此测试时会导致问题
TypeError: Cannot read property 'map' of undefined
我正在使用 24.1.0 的 Jest 最新版本,24.0.0 的 ts-jest,其 jest 配置为:
module.exports = {
transform: {
"^.+\\.tsx?$": "ts-jest",
},
testRegex: "(/src/.*)\\.(test.tsx?)$",
moduleFileExtensions: ["ts", "tsx", "js", "jsx", "json", "node"],
roots: ["<rootDir>/src"],
moduleNameMapper: {
"^.*\\.scss$": __dirname + "/jest.stub.ts",
"^components(.*)$": "<rootDir>/src/components$1",
"^helpers(.*)$": "<rootDir>/src/helpers$1",
"^pages(.*)$": "<rootDir>/src/pages$1",
"^services(.*)$": "<rootDir>/src/services$1",
"^state(.*)$": "<rootDir>/src/state$1",
"^fixtures(.*)$": "<rootDir>/src/fixtures$1",
"^constants(.*)$": "<rootDir>/src/constants$1",
},
setupFilesAfterEnv: ["./jest.setup.ts"],
};
有关如何解决此问题的任何建议都会很好,或者如果需要任何其他信息来帮助,请告诉我。谢谢