Search code examples
node.jsjestjspipets-jest

How to jest test (Body as any).pipe(zlib.createGunzip())?


I have been working on creating a unit test to test my import function implementation, but I can't get to pass from the .pipe() line. Here are some of my function lines for more context:

  const { Body } = await s3.send(command);
  console.log('body');
  console.log(Body);
  const input = (Body as any).pipe(zlib.createGunzip());
  console.log('done body');
  const lines = readline.createInterface({
    input,
    crlfDelay: Infinity,
  });
  console.log('done lines');

Here is my unit test code:

describe('Import function', function () {
  it('Import file', async () => {
    const stream = createReadStream('./tests/data/test.csv');
    const sdkStream = sdkStreamMixin(stream);
    s3Mock.on(GetObjectCommand).resolves({ Body: sdkStream });

    const event: any;
    let context: any;
    const result = await handler(event, context);
    console.log(result);
  });
});

The console.log('body'); and console.log(Body); lines are being printed and Body has the next value:

console.log
      ReadStream {
        fd: null,
        path: './tests/data/GLOBAL.csv',
        flags: 'r',
        mode: 438,
        start: undefined,
        end: Infinity,
        pos: undefined,
        bytesRead: 0,
        _readableState: ReadableState {
          objectMode: false,
          highWaterMark: 65536,
          ...

Even though Body has a value I am getting the next error when I run my test:

console.log
      TypeError: Cannot read properties of undefined (reading 'on')
          at ReadStream.Readable.pipe (node:internal/streams/readable:711:8)

Any ideas what's going on?

I implemented the s3 read mockup using this: https://www.npmjs.com/package/aws-sdk-client-mock After that I have tried to add another .on values to the s3Mock object but hasn't worked.


Solution

  • At the end I had to move those lines of code to a new file so I could mock that file import