TypeORM 关系未加载导致 NestJS 单元测试中类型不匹配

问题描述 投票:0回答:1

问题


我正在使用 NestJS、MySQL 和 TypeORM 构建一个小型后端 API。我有一个

Organisation
实体,与
KnowledgeDataPool[]
列表有关系。当我在 TypeORM 存储库上调用
find()
时,它会返回
Organisation
对象的列表,但没有
KnowledgeDataPool[]
关系,这是预期的。

测试控制器时出现问题。

organisationRepository.find()
方法被输入为返回
Promise<Organisation[]>
,但返回的对象不包含
knowledgeDataPools
字段。这会导致测试期间类型不匹配。

我应该将

organisationService.findAll()
的返回类型更改为
DeepPartial
Partial
吗?为什么
organisationRepository.find()
默认不返回
Partial

或者我错过了什么?

一些代码


组织类别:

@Entity()
export class Organisation {
  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  name: string;

  @OneToMany(
    () => KnowledgeDataPool,
    (knowledgeDataPool) => knowledgeDataPool.organisation,
    {
      cascade: true,
    },
  )
  @JoinTable()
  knowledgeDataPools: KnowledgeDataPool[]; // <--- Notice this relation.
}

我为我的组织提供服务:

@Injectable()
export class OrganisationService {
  constructor(
    @InjectRepository(Organisation)
    private organsiationRepository: Repository<Organisation>,
  ) {}

  ...

  findAll(): Promise<Organisation[]> {
    return this.organsiationRepository.find();
  }

  ...
}

还有一个调用此服务的控制器:

export class OrganisationController {
  constructor(private readonly organisationService: OrganisationService) {}

  ...

  @Get()
  @ApiOperation({ summary: 'Get all oranisations.' })
  findAll() {
    return this.organisationService.findAll();
  }

  ...
}

知道我何时想测试控制器:

describe('OrganisationController', () => {
  let organisationController: OrganisationController;
  let organisationService: OrganisationService;

  beforeEach(async () => {
    const mockOrganisationService = {
      findAll: jest.fn(),
      ...
    };

    const module: TestingModule = await Test.createTestingModule({
      controllers: [OrganisationController],
      providers: [
        {
          provide: OrganisationService,
          useValue: mockOrganisationService, // Use the mock service
        },
      ],
    }).compile();

    organisationController = module.get<OrganisationController>(OrganisationController);
    organisationService = module.get<OrganisationService>(OrganisationService);
  });

  it('should be defined', () => {
    expect(organisationController).toBeDefined();
  });

  describe('findAll', () => {
    it('should return an array of organisations', async () => {
      const result: = [
        {
          id: 1,
          name: 'Example', // No knowledgeDataPools in the actual result
        },
      ];

      // Mock the service method
      jest.spyOn(organisationService, 'findAll').mockResolvedValue(result); // <--- Error is shown here

      // Call the controller method
      expect(await organisationController.findAll()).toEqual(result);
    });
  });

  ...
} 

我收到此错误消息:

Argument of type '{ id: number; name: string; }[]' is not assignable to parameter of type 'Organisation[] | Promise<Organisation[]>'.
  Type '{ id: number; name: string; }[]' is not assignable to type 'Organisation[]'.
    Property 'knowledgeDataPools' is missing in type '{ id: number; name: string; }' but required in type 'Organisation'.
typescript jestjs nestjs typeorm
1个回答
0
投票

https://orkhan.gitbook.io/typeorm/docs/relational-query-builder

像这里你需要指定关系

 // Find all organisations with their related KnowledgeDataPool entities
  findAll(): Promise<Organisation[]> {
    return this.organisationRepository.find({
      relations: ['knowledgeDataPools'], // Specify the relation here
    });
  }
© www.soinside.com 2019 - 2024. All rights reserved.