Monday 22 April 2019

Jest tests (with just 1 suite) taking 21 seconds.

I have 1 test suite in my project, which uses the beforeAll hook to read five images from the file system.Then, the test simply asserts that two objects match.There are three files at play - the test suite, the file containing the function being tested, and a utility functions which permits returning a promise from fs.readFile()Utility Function: ```javscript const fs = require('fs');// Promisify the fs module for read file. module.exports.readFile = (filePath) => { return new Promise((resolve, reject) => { fs.readFile(filePath, (err, data) => { if (err) return reject(err); return resolve(data); }); }); } Function that is being tested: javascript // Append the size category property to all images. transformImageObjectProperties(images) { return images.map(image => ({ ...image, sizeCategory: 'unchanged' })); } Test File: // The general properties available on a received image from the client. const generalImageProperties = { filename: 'product-images', originalname: 'originalname', encoding: '7bit', mimetype: 'image/jpeg', buffer: null, size: 0 };// The array containing all image objects as if we have just received them from the client with multer. const completeTestImageObjects = [];beforeAll(async done => { // The images with which we will be performing tests. const fileNames = [ 'test-image-one.jpg', 'test-image-two.jpg', 'test-image-three.jpg', 'test-image-four.jpg', 'test-image-five.jpg', ];// Get array of pending promises const promises = fileNames.map(async fileName => { return await readFile(`${__dirname}/assets/${fileName}`); }); // Get all buffers from settled promises. const buffers = await Promise.all(promises); buffers.forEach((testImageBuffer, index) => { completeTestImageObjects.push({ ...generalImageProperties, originalname: fileNames[index], buffer: testImageBuffer, size: testImageBuffer.byteLength }); }); done(); });describe('Image Object Properties', () => {// Transform Image Object Properties test('should append the property "sizeCategory" with value "unchanged" to each supplied image', () => { // The transformed objects that came back from the class. const transformedImageObjects = transformImageObjectProperties(completeTestImageObjects); transformedImageObjects.forEach((imageObject, index) => { expect(imageObject).toEqual({ ...completeTestImageObjects[index], sizeCategory: 'unchanged' }); }); }); }); ``` The test itself takes 14 seconds, and the entire test suite takes 21 seconds to complete. I would appreciate any insight as to why this is taking so long. Thank you.

Submitted April 22, 2019 at 07:38PM by JamieCorkhill

No comments:

Post a Comment