Ale*_*ssi 16 typescript ts-jest
所以我有一个正在使用的项目:
在我开始编写测试之前,它工作得很好。测试文件位于每个实体文件夹内。例如:
Student
|- Student.ts
|- Student.test.ts
|- StudentService.ts
Run Code Online (Sandbox Code Playgroud)
当我运行 Jest 来执行测试时,一切都很好并且按预期工作。但是,如果我运行,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"]
}
Run Code Online (Sandbox Code Playgroud)
我的 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",
},
};
Run Code Online (Sandbox Code Playgroud)
据我所知,打字稿正在尝试编译我的测试文件,即使它们被设置为排除在 tsconfig 内部。
更多可能有用的信息:我有 jest、ts-jest 和 @types/jest 作为开发依赖项。我只有一个 tsconfig.json 文件和一个 jest.config.js
知道如何解决这个问题吗?
我忘记发布测试文件之一,尽管我认为它与问题无关或者是我的问题的原因......
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",
},
},
})
);
});
});
Run Code Online (Sandbox Code Playgroud)
错误堆栈
$ 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
Run Code Online (Sandbox Code Playgroud)
我的索引.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");
});
})();
Run Code Online (Sandbox Code Playgroud)
我的依赖项和开发依赖项
"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"
},
Run Code Online (Sandbox Code Playgroud)
Jam*_*mie 59
对于任何想globalSetup在 Jest 中工作并获得的
人ReferenceError: beforeAll is not defined- 我将为您节省几个小时的头撞桌子的时间:
jest.setup.tssetupFilesAfterEnv财产。IEsetupFilesAfterEnv: ['./jest.setup.ts']Jest 全局变量在或中不可用setupFilesglobalSetup
所以我才明白...这真的很愚蠢...
ormconfig.json 有一个扫描所有实体的路径,如下所示:
"entities": ["src/model/**/*.ts"],
Run Code Online (Sandbox Code Playgroud)
我不得不改为:
"entities": ["src/model/**/!(*.test.ts)"],
Run Code Online (Sandbox Code Playgroud)
这就是为什么我的一些测试文件被加载,然后抛出与未找到 Jest 函数相关的错误的原因。
在寻找一种以类似 tsconfig.json 的方式排除某些文件的方法后,我找到了这个解决方案,但是,TypeORM 没有排除参数,因此必须像上面那样完成。
感谢您的所有帮助。
| 归档时间: |
|
| 查看次数: |
19643 次 |
| 最近记录: |