This is my sample function and I want to create a test for it using jest, the S3 library test is already working but the "on" event listener gives an error
import { S3 } from 'aws-sdk';
import * as csvParse from 'fast-csv';
async function downloadCsvFile(fileName: string, bucketName: string): Promise<any> {
let parseStreamData;
var params = {
Bucket: bucketName,
Key: fileName,
};
try {
await new S3().headObject(params).promise();
let csvReadStream = new S3().getObject(params).createReadStream();
let csvFileArray: Array<any> = [];
parseStreamData = new Promise((resolve, reject) => {
csvParse
.parseStream(csvReadStream, { headers: true })
.on('data', function(data) {
csvFileArray.push(data);
})
.on('end', function() {
resolve(csvFileArray);
})
.on('error', function() {
reject('csv parse process failed');
});
});
} catch (error) {
console.log(error);
return [];
}
return await parseStreamData;
}
This is my test, I already mocked the parseStream function with the "on" event listeners, but when I run the test it gives me an error
import { bucketHandler } from './bucketHandler';
import { mocked } from 'ts-jest/utils';
import { parseStream } from "fast-csv";
import { S3 } from 'aws-sdk';
jest.mock('aws-sdk');
jest.mock("fast-csv");
describe('handler', () => {
test('downloadCsvFile', async () => {
mocked(S3).mockImplementationOnce((): any => ({
headObject: () => ({
promise: () => Promise.resolve(),
}),
}));
mocked(S3).mockImplementationOnce((): any => {
return {
getObject: () => {
return {
createReadStream: () => {
return {}
},
};
},
};
});
mocked(parseStream).mockImplementationOnce((): any => {
return {
on: () => {
return {
on: () => {
return {
on: () => {
return {}
}
}
}
}
},
}
});
expect(await bucketHandler.downloadCsvFile('1', '1')).toEqual([{}]);
});
});
This is the error when I run the test:
$ npm run test src/aws-s3/bucketHandler.test.ts
FAIL src/aws-s3/bucketHandler.test.ts (6.221s)
handler
× downloadCsvFile (5015ms)
● handler › downloadCsvFile
: Timeout - Async callback was not invoked within the 5000ms timeout specified by jest.setTimeout.Timeout - Async callback was not invoked within the 5000ms timeout specified by jest.setTimeout.Error:
8 |
9 | describe('handler', () => {
> 10 | test('downloadCsvFile', async () => {
| ^
11 | mocked(S3).mockImplementationOnce((): any => ({
12 | headObject: () => ({
13 | promise: () => Promise.resolve(),
at new Spec (node_modules/jest-jasmine2/build/jasmine/Spec.js:116:22)
at Suite.<anonymous> (src/aws-s3/bucketHandler.test.ts:10:5)
at Object.<anonymous> (src/aws-s3/bucketHandler.test.ts:9:1)
Test Suites: 1 failed, 1 total
Tests: 1 failed, 1 total
Snapshots: 0 total
Time: 6.77s, estimated 13s
Ran all test suites matching /src\\aws-s3\\bucketHandler.test.ts/i.