开玩笑:类型错误:无法解构“_graphql.default”的属性“print”,因为它未定义

m17*_*1vw 1 javascript node.js jestjs

我是 Jest 的新手,我正在尝试测试我的辅助功能。我目前没有使用任何 Typescript。

这是我运行时遇到的错误npm run test

TypeError: Cannot destructure property 'print' of '_graphql.default' as it is undefined.

助手.test.js

import getDuplicateError from '../../helpers/auth'

test('Check if email already exists', () => {
  error = "duplicate_email_key";
  expect(getDuplicateError(error)).toBe(true);
})
Run Code Online (Sandbox Code Playgroud)

auth.js

import graphql from "graphql";
const { print } = graphql;

export const getDuplicateError = (errors) => {
  /*...*/ // Actual implementation doesn't use print
};
Run Code Online (Sandbox Code Playgroud)

笑话配置.js

export default {
  preset: 'ts-jest/presets/js-with-babel',
  testEnvironment: "node",
  transform: {
    "^.+\\.(js|jsx)?$": "babel-jest",
    '^.+\\.(ts|tsx)?$': 'ts-jest',
  },
  transformIgnorePatterns: [
    "node_modules/(?!variables/.*)"
  ],
  coveragePathIgnorePatterns: [
    "/node_modules/"
  ]
};
Run Code Online (Sandbox Code Playgroud)

babel.config.json

{
  "presets": [
    [
      "@babel/preset-env",
      {
        "targets": {
          "node": true
        }
      }
    ]
  ]
}
Run Code Online (Sandbox Code Playgroud)

包.json

"devDependencies": {
    "@babel/preset-env": "^7.12.17",
    "babel-jest": "^26.6.3",
    "jest": "^26.6.3",
    "ts-jest": "^26.5.1",
    "ts-node": "^9.1.1"
  }
Run Code Online (Sandbox Code Playgroud)

即使print没有用于此功能(它用于其他功能),总体问题是由于此问题我现在无法测试任何内容,并且还需要能够将其用于其他功能。

是否需要某种配置才能使解构工作?我不能在其他库上使用解构吗?肯定会更喜欢能够像这样解构,因为我在代码中使用了很多解构。

如果我需要提供其他任何信息,请告诉我。

小智 5

尝试像这样导入

import * as graphql from "graphql";
const {print}=graphql;
Run Code Online (Sandbox Code Playgroud)

graphql不是从graphql包中导出的,因此它是undefined。同样,当您尝试print对其进行解构时,它会抛出错误。