如果我用 jest 运行测试,我总是收到错误消息
TypeError: this.subQuery is not a function
,并在 testModelDb.test.ts 文件中的标记行上引用
测试/jest.setup.ts
import 'reflect-metadata';
import dotenv from 'dotenv';
dotenv.config({ path: './.env.test' });
.env.测试
TYPEORM_CONNECTION=sqlite
TYPEORM_DATABASE=:memory:
TYPEORM_SYNCHRONIZE=true
TYPEORM_LOGGING=false
TYPEORM_ENTITIES=dist/models/**/*.js,modules/**/entity/*.ts
TYPEORM_MIGRATIONS=dist/services/db/seeding.js
TYPEORM_MIGRATIONS_RUN=true
src/models/test.model.ts
@Entity()
export default class TestModel {
@PrimaryGeneratedColumn()
id!: number;
@Column()
name!: string;
@OneToMany(() => OtherModel, (other) => other.testModel)
otherModels!: OtherModel[];
}
测试/testModelDb.test.ts
describe('Integrationtests', () => {
let connection: Connection;
beforeAll(async () => { connection = await createConnection(); });
afterAll(() => connection?.close());
beforeEach(async () => { await connection.synchronize(true); });
describe(`functions`, () => {
describe(`#function1()`, () => {
test('Test 1', async () => {
await connection
.createQueryBuilder()
.insert()
.into(TestModel) // <- here
.values([ {name: 'Test item 1'} ])
.execute();
expect(true).toBe(true);
});
});
});
});
在连接配置中,确保在
entities:[]
配置属性中添加了实体名称。
我遇到了这个问题并解决了在我的代码中删除 Typeorm 的一个容易忘记的数据源实例的问题,让我解释一下:
这是我的 ormconfig:
import 'dotenv/config'
import { DataSource } from "typeorm"
import { Users, Wallet } from "../entities"
const datasource = new DataSource({
type: "postgres",
host: process.env.DB_HOST,
port: Number(process.env.DB_PORT),
database: process.env.DB_DATABASE,
username: process.env.DB_USERNAME,
password: process.env.DB_PASSWORD,
entities: [Users, Wallet],
migrations: [__dirname + "/migrations/*{.js,.ts}"],
})
datasource.initialize();
export default datasource;
但是在我的代码中,我没有正确实例化这个脚本
import { Wallet } from '../entities';
import { DataSource } from 'typeorm'
import { IWalletRepository } from '../interfaces/wallet-repository'
import datasource from '../config/ormconfig'; // <---I imported my ormconfig
export class WalletRepository implements IWalletRepository{
AppDataSource: DataSource // <-- but I didn't passed here
async get (userId: Wallet['user_id']): Promise<Wallet> {
return this.AppDataSource
.getRepository(Wallet)
.createQueryBuilder('wallet')
...
我解决了这个问题,只需将我的 ormconfig 传递给 AppDataSource
AppDataSource: DataSource = datasource
希望对你有帮助