I have a simple function that calls my s3 service which will return a Promise
downloadFile(fileName: string): Promise<Readable> { console.log( "Downloading an object with key - ", fileName ); return this.s3service.getObject(fileName); }
I would like to mock the return of the object and assert it in the test like this:
it("should return readable if file present", async () => { const readable = new Readable(); readable.push("test"); jest .spyOn(s3service, "getObject") .mockImplementation(() => Promise.resolve(readable)); const file = await someService.downloadFile( TestConstants.reportName ); expect(file).toBe(readable); });
When i run the test, I face this error:
Error [ERR_METHOD_NOT_IMPLEMENTED]: The _read() method is not implemented at Readable.read (internal/streams/readable.js:642:9) at Readable.read (internal/streams/readable.js:481:10) at maybeReadMore (internal/streams/readable.js:629:12) at processTicksAndRejections (internal/process/task_queues.js:82:21) { code: ‘ERR_METHOD_NOT_IMPLEMENTED’
Would like some help on how I can properly mock a readable for example in this example
Advertisement
Answer
Your production code just forward response from the service to outside, then just mock getObject
to return anything, and expect the result should be getObject
result and the service function will have called with correct parameter:
it("should return readable if file present", async () => { const readable = "readable-object" as unknown as Readable; jest.spyOn(s3service, "getObject").mockResolvedValue(readable); const actual = await someService.downloadFile(TestConstants.reportName); expect(actual).toBe(readable); expect(s3service.getObject).toHaveBeenCalledWith(TestConstants.reportName); });