Here the code of my method which is used in the repository which I cover with unit tests.
private async getOrderDataForId(
orderData: any,
splitOrders: any,
responseOrders: any,
tenant_id: number,
trackingId?: string,
) {
this.#logger.info({
trackingId,
message: "get order data for given orderID - start",
data: { id: orderData.id, tenant_id: orderData.tenant_id },
});
const existingOrderData = await ManufactumCoreOrderService.getOrderById(
orderData.id,
orderData.tenant_id,
trackingId,
);
if (!existingOrderData || existingOrderData.length < 1) {
this.#logger.error({
trackingId,
message: "Order doesn't exist with id: ",
});
FbxError.throwBadRequest("WMS_Order_3", "Order doesn't exist with id: ");
}
const newOrderData = JSON.parse(JSON.stringify(existingOrderData));
this.#logger.info({
trackingId,
message: "get order data for given orderID - end",
data: newOrderData,
});
// optimize order_items
for (const [key] of Object.entries(splitOrders)) {
const position = parseInt(splitOrders[key][0].splitorder_position);
const number = parseInt(splitOrders[key][0].orderId);
if (key === "1") {
console.log("=======got into if block");
newOrderData.splitorder_position = position;
newOrderData.parent_id = orderData.id;
newOrderData.order_items = [];
for (const [index] of newOrderData.order_addresses.entries()) {
delete newOrderData.order_addresses[index].id;
}
for (const [index] of newOrderData.order_partners.entries()) {
delete newOrderData.order_partners[index].id;
delete newOrderData.order_partners[index].order_id;
}
// prepare new order
newOrderData.splitorder_number = number;
let total_weight = 0;
let total_volume = 0;
for (const splitOrderItem of splitOrders[key]) {
const index = existingOrderData.order_items.findIndex(
(item: any) => item.article_barcode == splitOrderItem.barcode && item.item_number === splitOrderItem.ManufactumPositionNumber,
);
if (index < 0) continue;
const orderItemData = existingOrderData.order_items[index];
orderItemData.amount = parseInt(splitOrderItem.amount);
orderItemData.item_number = splitOrderItem.ManufactumPositionNumber;
const articleId = orderItemData.article_id;
let articleData = await DB.query(
"select weight, length, width,height from articles where id = ?",
[articleId],
);
articleData = articleData[0];
const weight = articleData.weight;
const _total_weight = await this.calculateAnyISOUnitToAnyIsoUnit(
"KG",
"GRM",
weight * orderItemData.amount,
);
const width = articleData.width;
const height = articleData.height;
const length = articleData.length;
const realVolume = width * height * length;
const maxVolume = (realVolume + realVolume * 0.05) * orderItemData.amount;
total_volume += maxVolume;
total_weight += parseFloat(_total_weight);
orderItemData.WMS_Positionsnummer = parseInt(splitOrderItem.WMS_Positionsnummer);
if (existingOrderData.order_items[index]) {
existingOrderData.order_items[index].WMS_Positionsnummer = orderItemData.WMS_Positionsnummer;
}
newOrderData.order_items.push(existingOrderData.order_items[index]);
}
newOrderData.total_weight = total_weight + 200;
newOrderData.net_weight = total_weight;
newOrderData.volume = total_volume;
// create split order
this.#logger.info({
trackingId,
message: `Create split order for order id:${orderData.id} - start`,
data: newOrderData,
});
const newOrder = await ManufactumCoreOrderService.createOrder(newOrderData, orderData.tenant_id, trackingId, false);
if (!newOrder) {
this.#logger.error({ trackingId, message: "Failed to create order csv." });
FbxError.throwInternalError("WMS_Order_4", "Failed to create order csv.");
}
this.#logger.info({
trackingId,
message: `Create split order for order id:${orderData.id} - end`,
data: newOrder,
});
this.#logger.info({
trackingId,
message: `Update order id:${orderData.id} - start`,
data: newOrderData,
});
const updateQuery = "UPDATE orders SET erp_id = "" WHERE id = ?";
await DB.query(updateQuery, [orderData.id]);
this.#logger.info({
trackingId,
message: `Update order id:${orderData.id} - end`,
data: newOrder,
});
} else {
console.log("=======got into else block");
const newOrderManufactum: any = {
id: orderData.id,
new_order_number: formatNumbers(
parseInt(await this.getNewOrderNumber(orderData.tenant_id, "Split")),
10,
),
erp_id: existingOrderData.erp_id,
splitorder_number: number,
splitorder_position: position,
order_items: [],
};
for (const splitOrderItem of splitOrders[key]) {
newOrderManufactum.order_items.push({
new_order_item_number: await this.checkIfPositionIsStandardInt(
splitOrderItem.ManufactumPositionNumber,
orderData.id,
splitOrderItem.barcode,
tenant_id,
),
amount: parseInt(splitOrderItem.amount),
change_amount: false,
WMS_Positionsnummer: parseInt(splitOrderItem.WMS_Positionsnummer),
});
}
responseOrders.push(newOrderManufactum);
}
}
}
And here the code of the test. As you can see I mocked all async method and DB calls and still facing timeout. specifying different timeouts doesn’t help
describe("getOrderDataForId", () => {
let repo: any;
let orderDataMock: any = {
"id" : 303226,
"date" : "2024-04-10T14:00:11.000Z",
"erp_id" : "0089123048",
"tenant_id" : 4,
"shipping_service_id" : 2,
"shipping_type" : "",
"shipping_priority" : 5,
"customer_number_erp" : "",
"payment_method" : "",
"currency" : "",
"parent_id" : 4766580,
"splitorder_position" : 2,
"splitorder_number" : "98873524",
"order_status_id" : 47,
"bill_number" : "",
"sales_channel" : "",
"system_id" : 4,
"created_at" : "2024-04-10T16:00:11.000Z",
"updated_at" : "2024-04-11T16:11:07.000Z",
"order_type" : null,
"order_tracking_number" : null,
"tracking_id" : null,
"return_tracking_id" : null,
"wmsx_status" : "unprocessed",
"volume_measurement_unit_id" : 5,
"weight_measurement_unit_id" : 4,
"volume" : 25.65,
"total_weight" : 2486.0,
"incoterms1" : "FH",
"incoterms2" : "Frei Haus",
"net_weight" : "2140.000",
"number_of_packages" : 0,
"ship_condition" : "Z0",
"shipping_point" : "V007",
"sales_organisation" : "0200",
"warehouse_number" : "HER",
"desired_delivery_date" : "20240403220000",
"timezone" : "CET",
"description" : "{}",
"custom_attributes_MF" : "{"VSART":"SP","ZTERM":"D201","PAPERTYPE":"AT","BUNDESLAND":"Niederösterreich"}",
"is_valid" : 1,
"delivery_type" : "LF",
"document_status" : null,
"document_timestamp" : null,
"carrier_mapping_id" : 2,
"label_response" : null,
"Flyer" : null,
"cod_amount" : null,
"cod_purpose" : null,
"ps_sync_id" : null,
"processed_fine" : null,
"WMS_Auftragsnummer" : null,
"WMS_Teil_Auftragsnummer" : null,
"drop_off_point" : null,
"error_description" : "Failed to detect carrier. Country short name: AT, sales organisation: 200, VSART: SP, ship_condition: Z0",
"packaging_id" : null,
"fine_status" : null,
"fine_processed" : null,
"channel_id" : null,
"channel_sign" : null,
"channel_no" : null,
"item_count" : null,
"warehouse_id" : null,
"priority" : null,
"cancel_reason_code" : null,
"cancel_reason" : null,
"carrier" : null,
"merchant_id" : null,
"integrator" : null,
"order_items" : [{"id": 2290664, "amount": 1, "article_id": 2939, "article_name": "Balkonkasten Stahl verzinkt gross", "article_barcode": "2050000804168", "article_description": "", "article_weight": 2.14, "erp_id": "000000000000018996", "hazardus_material_number": null, "short_text": "Balkonkasten Stahl verzinkt gross", "sales_unit_id": 1, "sales_unit_iso_measure": "CMT", "item_hierarchy": "000000", "loading_group": "0003", "partial_delivery": "C", "overdelivery_percentage": 0, "underdelivery_percentage": 0, "movement_type": "601", "reference_movement_type": null, "movement_indicator": "L", "cumulated_batch_quantity": "0.000", "distribution_channel": "10", "division": "01", "plant": "0100", "storage_location": "L007", "profit_centre": null, "number_profitability": "0000000000", "sales_item_number": "000000", "item_number": "000010", "sales_document": "0852011163", "sales_document_item": "000010", "sales_document_category": "C", "document_date": "20240402", "order_date_customer": null, "order_date_to_party": "00000000", "date_of_call_off": null, "weight": 2140, "material_type": "HAWA", "article_width": 19, "article_length": 91, "article_height": 15, "article_length_measurement_unit": "CM", "article_weight_measurement_unit": "KG", "WMS_Positionsnummer": "1", "change_amount": 0}],
"order_addresses" : [{"id": 1060667, "salutation": "Firma", "name": null, "first_name": null, "last_name": null, "full_name": "Schlosserei Bock GmbH", "company_name": "", "street": "Ascherstraße", "street_number": "0180795", "house_number": "10", "postal_code": "2734", "city": "Puchberg am Schneeberg", "email": null, "country_short_name": "AT", "contact": "02636 2303", "floor": null, "room_number": null, "erp_id": "0026824582", "county": null, "address_notes": null, "fax": null, "time_zone": "CET", "address_info": {"AT":{"COUNTRYISO":"AT","LANGU_ISO":"DE"}}},{"id": 1060668, "salutation": "Firma", "name": null, "first_name": null, "last_name": null, "full_name": "Schlosserei Bock GmbH", "company_name": "", "street": "Ascherstraße", "street_number": "0180795", "house_number": "10", "postal_code": "2734", "city": "Puchberg am Schneeberg", "email": null, "country_short_name": "AT", "contact": "02636 2303", "floor": null, "room_number": null, "erp_id": "0026824582", "county": null, "address_notes": null, "fax": null, "time_zone": "CET", "address_info": {"AT":{"COUNTRYISO":"AT","LANGU_ISO":"DE"}}}],
"order_partners" : null,
"shipping_service_name" : "DHL",
"order_status_name" : "Carrier and shipping type are not determined.",
"order_status_code" : "error_2000",
"shipped_out_date" : null,
"invoice_number" : null,
"weight_measurement_unit" : "G",
"volume_measurement_unit" : "CDM"
};
let responseOrders: any = orderDataMock;
let splitOrders: any = {
1: [
{
splitorder_position: 1,
orderId: 123,
},
{
splitorder_position: 2,
orderId: 124,
},
{
splitorder_position: 3,
orderId: 125,
},
],
};
beforeEach(async () => {
repo = new ManufactumWmsxOrderRepository();
ManufactumCoreOrderService.getOrderById = vi.fn().mockResolvedValue(orderDataMock)
DB.query = vi.fn().mockResolvedValue(orderDataMock);
DB.query = vi.fn().mockResolvedValue(true);
repo.calculateAnyISOUnitToAnyIsoUnit = vi.fn().mockResolvedValue(1);
ManufactumCoreOrderService.createOrder = vi.fn().mockResolvedValue(orderDataMock);
repo.getNewOrderNumber = vi.fn().mockResolvedValue("0088123456");
repo.checkIfPositionIsStandardInt = vi.fn().mockResolvedValue("000390");
})
test("should update responseOrders array", async () => {
await repo.getOrderDataForId(orderDataMock, splitOrders, responseOrders, 4);
})
}, { timeout:10000 })
I’ve tried mocking all async methods and db calls with vi.fn(). Also, tried to change timeout.