I am attempting to use the class-validator module to confirm my object is valid when using a Mapper code.
order.entity.ts
import {
ArrayMinSize,
IsArray,
IsBoolean,
IsDate,
IsDateString,
IsInt,
IsOptional,
IsString,
ValidateNested,
} from 'class-validator';
import { Transform, Type } from 'class-transformer';
export class Order {
@IsInt()
@IsOptional()
OrderId?: number;
@IsString()
@IsOptional()
RetailerName?: string | null;
@IsString()
RetailerOrderId: string;
@IsString()
@IsOptional()
Brand?: string | null;
}
I have a mapper set up as follows: data.mapper.ts
import { Order } from './entities/Order.entity';
import { transformAndValidate } from 'class-transformer-validator';
export class OrderMapper {
public static async toDomainFromMessage(raw: any): Promise<Order> {
const order = new Order();
order.RetailerName =
raw.source ??
(() => {
new Error('Retailer Name is missing');
})();
order.RetailerOrderId = raw.externalOrderId
? raw.externalOrderId.toString()
: null;
const result = await transformAndValidate(Order, order)
.then((orderObject: Order) => {
return orderObject;
})
.catch((err) => {
throw err;
});
return result;
}
}
I test by passing in an object like this
const order = {
orderId: 12345678,
shipping_country_code: 'US',
orderTypes: [
{
orderTypeLabel: 'Wholesale',
orderTypeId: '14',
},
],
};
Since it is missing the ExternalOrder field, it throws an array of errors of type Validation Error.
I have tried catching the error using this code, but cannot figure out the expect command I need to use to verify I have some Validation Error objects within the caught error variable
try {
const order = await OrderMapper.toDomainFromMessage(order);
} catch (e) {
console.log(e);
}
You can use the Jest expect
function with a custom matcher to verify that the caught error is an instance of the ValidationError
class from the class-validator
module, and that it contains the expected number of errors.
Add this code under the catch block.
expect(e).toHaveLength(length);
e.forEach((error) => {
expect(error).toBeInstanceOf(ValidationError);
});