BramComyn / safeguard-fetch

0 stars 0 forks source link

Issue when testing ``TurtleDownloader`` #57

Closed BramComyn closed 1 month ago

BramComyn commented 1 month ago

I am writing this issue, because I have spend a long time trying to figure out how to be able to test the download-method of my use case TurtleDownloader. In my last two tests I do this:

await expect(
  downloader.download(url),
).rejects.toThrow(Error);

or

await expect(
  downloader.download(url),
).resolves.toEqual(someBuffer);

The problem is that inside the download-method, I await a promise that rejects or resolves based on what event gets triggered first:

// We want to await the end or error of the request,
// so that we can be sure the entire buffer is filled and returned.
return new Promise<Uint8Array>((resolve, reject): void => {
  request.on('close', (): void => resolve(this._buffer.slice(0, this.downloadedSize)));
  request.on('error', reject);
});

However, I have no possibility to trigger the event being fired, because the listener is only attached in this promise and neither my test, nor that function will continue executing when this promise has not been resolved. I am trying to figure out how I can do this, but haven't found any clues in the jest documentation or other people's issues.

BramComyn commented 1 month ago

This code is located in src/turtle-downloader and test/unit/turtle-downloader and currently only on the use-cases branch

RubenVerborgh commented 1 month ago

Mock the thing that creates the request?

BramComyn commented 1 month ago

That already happens in the beforeEach of my test:

request = new EventEmitter() as any;
request.close = jest.fn();

requester = {
  addRequestEventHandler: jest.fn(),
  connectAndRequest: jest.fn().mockReturnValue(request),
} as any;

I also tried mocking the implementation to call request.emit(event) there, but this connectAndRequest-method is also called before the handler is set, so probably, I should re-evaluate how I can set this handler and achieve the functionality I desire to.

RubenVerborgh commented 1 month ago

You can also mock on 🙃

BramComyn commented 1 month ago

Woops