Typescript with Jest - "ReferenceError: beforeAll is not defined"
Typescript with Jest - "ReferenceError: beforeAll is not defined"
所以我有一个正在使用的项目:
- 打字稿
- TypeORM
- 类型-graphql
- 开玩笑
在我开始编写测试之前,它工作得很好。测试文件位于每个实体文件夹中。例如:
Student
|- Student.ts
|- Student.test.ts
|- StudentService.ts
当我 运行 开玩笑地执行我的测试时,一切都很好并且按预期工作。但是,如果我 运行 nodemon --exec ts-node src/index.ts
我得到第一个 Jest 相关函数的错误,无论是 beforeAll()、afterAll()、describe()...
我的 tsconfig.json 是:
{
"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是:
module.exports = {
preset: "ts-jest",
testEnvironment: "node",
roots: ["./src"],
testMatch: [
"**/__tests__/**/*.+(ts|tsx|js)",
"**/?(*.)+(spec|test).+(ts|tsx|js)",
],
transform: {
"^.+\.(ts|tsx)$": "ts-jest",
},
};
据我所知,typescript 正在尝试编译我的测试文件,即使它们被设置为在 tsconfig 中排除。
更多可能有用的信息:
我有 jest、ts-jest 和 @types/jest 作为 devdependencies。
我只有一个 tsconfig.json 文件和一个 jest.config.js
知道如何解决这个问题吗?
更新 1
我忘记了 post 测试文件之一,虽然我不认为它与问题有关或者是我的问题的原因...
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
错误堆栈
$ 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
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
我的依赖和开发依赖
"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"
},
检查 package.json
是否具有所有依赖项:
{
"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
它有效。
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
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
function sum(x:number, y:number):number {
return x + y;
}
export default sum
运行 与 nodemon
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
所以我想通了...真的很傻...
ormconfig.json有一个扫描所有实体的路径,像这样:
"entities": ["src/model/**/*.ts"],
我不得不改为:
"entities": ["src/model/**/!(*.test.ts)"],
这就是为什么我的一些测试文件被加载然后抛出与未找到 Jest 函数相关的错误的原因。
我在搜索以类似方式排除某些文件后找到了这个解决方案 tsconfig.json,但是,TypeORM 没有排除参数,因此必须像上面那样完成。
Github issue with the suggestion
感谢大家的帮助。
对于任何想要 globalSetup
在 Jest 工作并获得
ReferenceError: beforeAll is not defined
- 我会为你节省几个小时的头撞桌子的时间:
- 定义您的安装文件 -
jest.setup.ts
- 使用
setupFilesAfterEnv
属性。即 setupFilesAfterEnv: ['./jest.setup.ts']
Jest 全局变量在setupFiles
或globalSetup
中不可用
所以我有一个正在使用的项目:
- 打字稿
- TypeORM
- 类型-graphql
- 开玩笑
在我开始编写测试之前,它工作得很好。测试文件位于每个实体文件夹中。例如:
Student
|- Student.ts
|- Student.test.ts
|- StudentService.ts
当我 运行 开玩笑地执行我的测试时,一切都很好并且按预期工作。但是,如果我 运行 nodemon --exec ts-node src/index.ts
我得到第一个 Jest 相关函数的错误,无论是 beforeAll()、afterAll()、describe()...
我的 tsconfig.json 是:
{
"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是:
module.exports = {
preset: "ts-jest",
testEnvironment: "node",
roots: ["./src"],
testMatch: [
"**/__tests__/**/*.+(ts|tsx|js)",
"**/?(*.)+(spec|test).+(ts|tsx|js)",
],
transform: {
"^.+\.(ts|tsx)$": "ts-jest",
},
};
据我所知,typescript 正在尝试编译我的测试文件,即使它们被设置为在 tsconfig 中排除。
更多可能有用的信息: 我有 jest、ts-jest 和 @types/jest 作为 devdependencies。 我只有一个 tsconfig.json 文件和一个 jest.config.js
知道如何解决这个问题吗?
更新 1
我忘记了 post 测试文件之一,虽然我不认为它与问题有关或者是我的问题的原因...
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
错误堆栈
$ 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
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
我的依赖和开发依赖
"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"
},
检查 package.json
是否具有所有依赖项:
{
"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
它有效。
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
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
function sum(x:number, y:number):number {
return x + y;
}
export default sum
运行 与 nodemon
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
所以我想通了...真的很傻...
ormconfig.json有一个扫描所有实体的路径,像这样:
"entities": ["src/model/**/*.ts"],
我不得不改为:
"entities": ["src/model/**/!(*.test.ts)"],
这就是为什么我的一些测试文件被加载然后抛出与未找到 Jest 函数相关的错误的原因。
我在搜索以类似方式排除某些文件后找到了这个解决方案 tsconfig.json,但是,TypeORM 没有排除参数,因此必须像上面那样完成。
Github issue with the suggestion
感谢大家的帮助。
对于任何想要 globalSetup
在 Jest 工作并获得
ReferenceError: beforeAll is not defined
- 我会为你节省几个小时的头撞桌子的时间:
- 定义您的安装文件 -
jest.setup.ts
- 使用
setupFilesAfterEnv
属性。即setupFilesAfterEnv: ['./jest.setup.ts']
Jest 全局变量在setupFiles
或globalSetup