首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Jest的类型记录- "ReferenceError: beforeAll未定义“

Jest的类型记录- "ReferenceError: beforeAll未定义“
EN

Stack Overflow用户
提问于 2021-02-05 01:20:41
回答 3查看 10.4K关注 0票数 9

所以我有一个我正在使用的项目:

  • 打字本
  • TypeORM
  • 类型图
  • 取笑

在我开始写测试之前,我一直让它正常工作。测试文件位于每个实体文件夹中。例如:

代码语言:javascript
运行
复制
  Student
  |- Student.ts
  |- Student.test.ts
  |- StudentService.ts

当我运行Jest来执行我的测试时,一切都很好,并按预期工作。但是,如果我运行nodemon --exec ts-node src/index.ts,我会得到第一个Jest相关函数的错误,不管它是beforeAll()、afterAll()、describe().

我的tsconfig.json是:

代码语言:javascript
运行
复制
{
  "compilerOptions": {
    "target": "es6",
    "module": "commonjs",
    "lib": ["dom", "es6", "es2017", "esnext.asynciterable"],
    "sourceMap": true,
    "outDir": "./dist",
    "moduleResolution": "node",

    "types": ["jest", "node"],

    "removeComments": true,
    "noImplicitAny": true,
    "strictNullChecks": true,
    "strictFunctionTypes": true,
    "noImplicitThis": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "noImplicitReturns": true,
    "noFallthroughCasesInSwitch": true,
    "allowSyntheticDefaultImports": true,
    "esModuleInterop": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true
  },
  "include": ["**/*.ts"],
  "exclude": ["node_modules", "**/*.test.ts", "**/*.spec.ts"]
}

我的jest.config.js是:

代码语言:javascript
运行
复制
module.exports = {
  preset: "ts-jest",
  testEnvironment: "node",
  roots: ["./src"],
  testMatch: [
    "**/__tests__/**/*.+(ts|tsx|js)",
    "**/?(*.)+(spec|test).+(ts|tsx|js)",
  ],
  transform: {
    "^.+\\.(ts|tsx)$": "ts-jest",
  },
};

据我所理解,类型记录正在尝试编译我的测试文件,即使它们被设置为排除在tsconfig中。

更多可能有用的信息:我有jest、ts-jest和@type/jest作为dev依赖性。我只有一个tsconfig.json文件和一个jest.config.js

知道怎么解决这个问题吗?

更新1

我忘了发一个测试文件,虽然我不认为它与问题有关,或者是我的问题的原因。

代码语言:javascript
运行
复制
import { createTestConnection } from "../../test/createTestConnection";
import { graphqlCall } from "../../test/graphqlCall";
import { Connection } from "typeorm";

let conn: Connection;

beforeAll(async () => {
  console.log("Test started");

  conn = await createTestConnection(true);
});

afterAll(() => {
  conn.close();
});

const addStudentWithoutGuardian = `
  mutation addStudentWithoutGuardian($studentInput: StudentInput!) {
  addStudent(studentInput: $studentInput) {
    id
  }
}
`;

describe("Student", () => {
  it("create only with basic information", async () => {
    console.log(
      await graphqlCall({
        source: addStudentWithoutGuardian,
        variableValues: {
          studentInput: {
            firstName: "Harry",
            lastName: "Smith",
            dateOfBirth: "1997-01-30",
            pronoun: 0,
            gender: 0,
            phone: "1231231234",
            email: "harry@gmail.com",
            addressLine1: "123 Avenue",
            city: "Toronto",
            state: "Ontario",
            postalCode: "X1X1X1",
            gradeLevel: "grade level",
          },
        },
      })
    );
  });
});

更新2

错误堆栈

代码语言:javascript
运行
复制
$ nodemon --exec ts-node src/index.ts
[nodemon] 2.0.7
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): *.*
[nodemon] watching extensions: ts,json      
[nodemon] starting `ts-node src/index.ts`   
(node:11716) UnhandledPromiseRejectionWarning: ReferenceError: beforeAll is not defined
    at Object.<anonymous> (G:\Documents\repos\tms\server\src\model\Student\Student.test.ts:7:1)
    at Module._compile (internal/modules/cjs/loader.js:1063:30)
    at Module.m._compile (G:\Documents\repos\tms\server\node_modules\ts-node\src\index.ts:1056:23)
    at Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
    at Object.require.extensions.<computed> [as .ts] (G:\Documents\repos\tms\server\node_modules\ts-node\src\index.ts:1059:12)
    at Module.load (internal/modules/cjs/loader.js:928:32)
    at Function.Module._load (internal/modules/cjs/loader.js:769:14)
    at Module.require (internal/modules/cjs/loader.js:952:19)
    at require (internal/modules/cjs/helpers.js:88:18)
    at G:\Documents\repos\tms\server\src\util\DirectoryExportedClassesLoader.ts:41:22
(Use `node --trace-warnings ...` to show where the warning was created)
(node:11716) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:11716) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
[nodemon] clean exit - waiting for changes before restart

更新3

我的index.ts

代码语言:javascript
运行
复制
import "reflect-metadata";
import { createConnection } from "typeorm";
import express from "express";
import { ApolloServer } from "apollo-server-express";
import cors from "cors";
import { createSchema } from "./utils/createSchema";

(async () => {
  const app = express();

  app.use(
    cors({
      origin: ["http://localhost:3000"],
      credentials: true,
    })
  );

  await createConnection();

  const apolloServer = new ApolloServer({
    schema: await createSchema(),
    context: ({ req, res }) => ({ req, res }),
  });

  apolloServer.applyMiddleware({ app, cors: false });

  app.listen(4000, () => {
    console.log("Express server started");
  });
})();

更新4

我的依赖和devDependencies

代码语言:javascript
运行
复制
"dependencies": {
    "apollo-server-express": "^2.19.2",
    "class-validator": "^0.13.1",
    "cors": "^2.8.5",
    "dotenv": "^8.2.0",
    "express": "^4.17.1",
    "faker": "^5.2.0",
    "graphql": "^15.4.0",
    "pg": "^8.5.1",
    "reflect-metadata": "^0.1.13",
    "type-graphql": "^1.1.1",
    "typeorm": "^0.2.30",
    "typeorm-seeding": "^1.6.1"
  },
  "devDependencies": {
    "@types/express": "^4.17.11",
    "@types/faker": "^5.1.6",
    "@types/jest": "^26.0.20",
    "@types/node": "^14.14.21",
    "jest": "^26.6.3",
    "nodemon": "^2.0.7",
    "ts-jest": "^26.5.0",
    "ts-node": "^9.1.1",
    "typescript": "^4.1.3"
  },
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2021-02-05 05:49:53

所以我想出来了..。真的很傻..。

ormconfig.json具有扫描所有实体的路径,如下所示:

代码语言:javascript
运行
复制
"entities": ["src/model/**/*.ts"],

我不得不换到:

代码语言:javascript
运行
复制
"entities": ["src/model/**/!(*.test.ts)"],

这就是为什么我的一些测试文件被加载,然后抛出与Jest函数相关的错误的原因。

我找到了这个解决方案,在搜索了一种类似于tsconfig.json所做的排除某些文件的方法之后,然而,TypeORM没有排除参数,所以必须像上面这样做。

Github提出建议

谢谢你的帮助。

票数 2
EN

Stack Overflow用户

发布于 2021-09-13 21:37:15

对于那些想要在Jest工作的globalSetupReferenceError: beforeAll is not defined的人来说,我可以帮你省下几个小时的时间,把你的头撞到桌子上:

  1. 定义安装文件- jest.setup.ts
  2. 使用setupFilesAfterEnv属性。即setupFilesAfterEnv: ['./jest.setup.ts']

Jest globals是setupFilesglobalSetup中不可用的

票数 32
EN

Stack Overflow用户

发布于 2021-02-05 03:32:54

检查package.json是否具有所有依赖项:

代码语言:javascript
运行
复制
{
  "name": "ts_test",
  "version": "1.0.0",
  "main": "index.js",
  "license": "MIT",
  "devDependencies": {
    "jest": "^26.6.3",
    "ts-jest": "^26.5.0",
    "ts-node": "^9.1.1",
    "typescript": "^4.1.3"
  }
}

我跟你说过:yarn jest,它有效。

代码语言:javascript
运行
复制
 PASS  src/sum.test.ts
  ✓ adds 1 + 2 to equal 3 (4 ms)

  console.log
    Test started

      at src/sum.test.ts:4:11

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        4.023 s
Ran all test suites.
Done in 5.06s.

sum.test.ts

代码语言:javascript
运行
复制
import sum from './sum';

beforeAll(async () => {
  console.log("Test started");
});

test('adds 1 + 2 to equal 3', () => {
  expect(sum(1, 2)).toBe(3);
});

sum.ts

代码语言:javascript
运行
复制
function sum(x:number, y:number):number {
  return x + y;
}

export default sum

带鼻涕跑

代码语言:javascript
运行
复制
yarn nodemon --exec ts-node src/sum.ts
yarn run v1.22.4
$ /home/.../ts_test/node_modules/.bin/nodemon --exec ts-node src/sum.ts
[nodemon] 2.0.7
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): *.*
[nodemon] watching extensions: ts,json
[nodemon] starting `ts-node src/sum.ts`
[nodemon] clean exit - waiting for changes before restart
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66056282

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档