Jest测试失败,错误为“未为此实体设置数据源”

4si2a6ki  于 2023-10-14  发布在  Jest
关注(0)|答案(1)|浏览(104)

我正在构建一个nodejs| express API与typeprofile和一切正常工作时,调用路由通过 Postman 或一些客户端。这个问题出现在使用jest进行的测试中,我得到了以下错误:“未为该实体设置数据源”。我错过什么了吗?

  • 节点:16.15.1
  • “超级测试”:“^6.2.4”,
  • “ts-node”:“^10.9.1”,
  • “类型”:“^0.3.7”,
  • “typescript”:“^4.7.4”
  • “node-postgres”:“^0.6.2”,
  • “form”:“^7.1.0”,
  • “pg”:“^8.7.3”,
  • “jest”:“^28.1.3”,
  • “ts-jest”:“^28.0.7”
  • “express”:“^4.18.1”,

我使用Postgres数据库进行测试。
jest config:

module.exports = async () => {
    return {
        preset: "ts-jest",
        testEnvironment: "node",
        verbose: true,
        moduleNameMapper: {
            "@exmpl/(.*)": "<rootDir>/src/$1"
          },
      };
}

数据源文件:

import { DataSource } from "typeorm"
import path from "path"

export const AppDataSource = new DataSource({
    name: "default",
    migrationsTableName: 'migrations',
    type: "postgres",
    host: process.env.POSTGRES_HOST,
    port: Number(process.env.POSTGRES_PORT),
    username: process.env.POSTGRES_USER,
    password: process.env.POSTGRES_PASSWORD,
    database: process.env.POSTGRES_DB,
    synchronize: false,
    logging: false,
    entities: [path.join(__dirname, '../entities/**/*.entity.js')],
    migrations: [path.join(__dirname, '../migrations/**/*.js')],
    subscribers: [],
    cache: true
})

测试文件:

import path from "path";
import request from "supertest"
import { AppDataSource } from "../src/db/DataSource"
import { Role } from "../src/entities/User/Role.enum"
import app from "../src/App"

let connection: any;

describe('Auth', () => {
    beforeAll(async () => {
        AppDataSource.setOptions({
            entities: [path.join(__dirname, '../dist/entities/**/*.entity.js')],
            migrations: [path.join(__dirname, '../dist/migrations/**/*.js')],
            synchronize: true,
            dropSchema: true,
        })
        connection = await AppDataSource.initialize()
        await connection.synchronize(true)
    })

    afterAll(async () => {
        await connection.destroy()
    })

    test('should signUp', async () => {
        const response = await request(app)
        .post('/auth/register')
        .send({
            firstName: "test",
            lastName: "test",
            email: "[email protected]",
            role: Role.USER,
            status: "active",
            password: "Pa$$w0rd"
        })

        console.log(response.body)

        //Temporary pass
        expect(2+2).toBe(4)
    })
})

Babel配置:

module.exports = {
    presets: [
      ['@babel/preset-env', {targets: {node: 'current'}}],
      '@babel/preset-typescript',
    ],
    plugins: [
        ['@babel/plugin-syntax-decorators', { decoratorsBeforeExport: true }],
        ['@babel/plugin-proposal-decorators', { decoratorsBeforeExport: true }],
        ['@babel/plugin-proposal-class-properties', { "loose": true }],
    ]
  };

tsconfig:

{
  "compilerOptions": {

    /* Language and Environment */
    "target": "es2016",                                 
    "experimentalDecorators": true,                   
    "emitDecoratorMetadata": true,                  

    /* Modules */
    "module": "commonjs",                               
    "moduleResolution": "node",                       
    "rootDirs": ["src/", "config/"],                                   
    "typeRoots": ["./node_modules/@types", "src/typings"],                                  

    /* JavaScript Support */

    /* Emit */
    "declaration": true,                              
     "sourceMap": true,                                
     "outDir": "dist",                                   
     "removeComments": true,                           

    /* Interop Constraints */
    "allowSyntheticDefaultImports": true,           
    "esModuleInterop": true,                             
    "forceConsistentCasingInFileNames": true,           

    /* Type Checking */
    "strict": true,                                     
    "noImplicitAny": true,                            
    "strictNullChecks": true,                         
    "strictPropertyInitialization": false,             

    /* Completeness */
    "skipLibCheck": true                                
  },
  "include": ["src/**/*"]
}
oyt4ldly

oyt4ldly1#

经过一点研究,我发现问题是实体文件夹的错误路径。它不应该是编译文件的路径,而是类型脚本源文件的路径。
我把这个答案贴出来,以防有人有同样的问题。
我替换了这个:

AppDataSource.setOptions({
   entities: [path.join(__dirname, '../dist/entities/**/*.entity.js')],
   migrations: [path.join(__dirname, '../dist/migrations/**/*.js')],
   synchronize: true,
   dropSchema: true,
})

用这个:

AppDataSource.setOptions({
   entities: entities: [path.join(__dirname, '../../src/entities/**/*.entity.ts')],
   migrations: [path.join(__dirname, '../../src/migrations/**/*.ts')],
   synchronize: true,
   dropSchema: true,
})

我不知道为什么会这样,所以如果有人知道解释这将是伟大的。

相关问题