javascript - "Navbar refers to a value, but is being used as a type here"在测试时尝试呈现我的组件的浅拷贝

标签 javascript typescript testing jestjs enzyme

我正在尝试为我的 React 组件编写测试,使用 TypeScript,Jest 作为我的测试运行器,并使用 Enzyme 来测试我的 React 组件。每当我将我的组件传递到 shallow Enzyme 函数时,我都会收到 ts 错误“'Navbar' 引用了一个值,但在这里被用作类型。”,并且在下面我收到 eslint 错误“解析错误:预期为“>”。

我在其他一些组件上尝试过,当作为参数传递给 shallow 函数时,所有组件都出现相同的错误。我怀疑这可能与我的 TS 配置有关,但就我的生活而言,我似乎找不到解决方案。

这是 Navbar.tsx 的代码:

import React from 'react';
import { shallow } from 'enzyme';
import Navbar from './Navbar';

describe('Navbar component', () => {
    let component;
    beforeEach(() => {
        component = shallow(<Navbar />); // Error being desplayed here
    });

    it('should render without errors', () => {
        expect(component).toMatchInlineSnapshot();
        expect(component.length).toBe(1);
        expect(component).toBeTruthy();
    });
});

同时发布我的配置文件:

配置文件:

{
  "compilerOptions": {
    "target": "es5",
    "lib": [
      "dom",
      "dom.iterable",
      "esnext"
    ],
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "react"
  },
  "parserOptions": {
    "ecmaVersion": 6,
    "sourceType": "module",
    "ecmaFeatures": {
      "jsx": true
    }
  },
  "include": ["src/**/*"],
  "exclude": ["node_modules", "**/*.spec.ts", "**/*.test.ts"]
}

开 Jest .config.ts:

module.exports = {
    roots: ['<rootDir>/src'],
    transform: {
        '^.+\\.tsx?$': 'ts-jest',
    },
    testRegex: '(/__tests__/.*|(\\.|/)(test|spec))\\.tsx?$',
    moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'],
    snapshotSerializers: ['enzyme-to-json/serializer'],
    setupTestFrameworkScriptFile: '<rootDir>/src/setupEnzyme.ts',
};

enzyme 设置:

import { configure } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import 'jest-enzyme';

configure({ adapter: new Adapter(), disableLifecycleMethods: 

最佳答案

您是否尝试过更改文件名? 我的组件.test.tsx 另外,你有没有安装 types of jest 之类的 npm i -D @types/jest。 我的意思是我这么说是因为如果你看一下 jest 配置,它说的是 testRegex。你有这样的 __tests__/*.(test|spec).txs 测试必须位于 tests 文件夹中,并且名称必须为:MyComponent.test.tsx

关于javascript - "Navbar refers to a value, but is being used as a type here"在测试时尝试呈现我的组件的浅拷贝,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58341545/

相关文章:

javascript - 如何使用 jQuery 使用不同的类标识符定位每个元素?

typescript - 如何处理 typescript 定义文件中的类型名称冲突

javascript - 如何在此函数中提供 Observable?

javascript - 如何在angular2 webpack typescript 中包含第三方javascript库

python - 将 JSON 对象发送到服务

javascript - 即使存在调用同源策略的概念,我们如何加载图像?

javascript - 基于语言的条件渲染 : combining props and constants to render component

javascript - jquery延迟文档准备好功能的秒数?

testing - "history"和 "retries"在 Allure 中到底意味着什么?

bash - 单元测试 Bash 脚本