首页 > 解决方案 > 如何使用 jest 测试包含数组的对象

问题描述

我正在尝试测试包含几个复杂字段的对象:

  1. 其中一个字段包含对象数组。
  2. 其中一个字段包含对象,其字段之一包含对象数组。

我尝试使用expect(createdRequest).toEqual(expect.objectContaining(originRequestData));. 我也尝试使用expect().toMatchObject()和其他很多方法,但没有一个有效。

这是我要测试的对象的接口

export interface IRequest {
  id?: string;
  openDate?: Date;
  closeDate: Date;
  approvals:
  {
    replyUser: Types.ObjectId;
    answer: number | null;
  }[]; // Array of objects
  target: {
    recordId?: Types.ObjectId;
    collectionName: string;
  };
  action: {
    actionType: ActionType;
    additionalData: AdditonalDataType[]; // Array of objects. note: AdditonalDataType  
                                         // is an interface of object.
  };
  comment?: string;
  requester: Types.ObjectId;
}

我使用的模拟:

export const validRequest: IRequest = {
  closeDate: new Date('12/10/2030'),
  approvals: [{
    replyUser: new Types.ObjectId(),
    answer: 2,
  }],
  target: {
    recordId: Types.ObjectId(),
    collectionName: 'occupations',
  },
  action: {
    actionType: ActionType.create,
    additionalData: [{
      field: 'job',
      value: 'chef',
    }],
  },
  requester: new Types.ObjectId(),
};

我写的测试

test('Should create a single request', async () => {
  const createdRequest: IRequest = await RequestsManager.create(validRequest);
  expect(createdRequest).toEqual(expect.objectContaining(validRequest));
});

我收到的错误在此处输入图像描述

标签: javascripttypescriptjestjs

解决方案


推荐阅读