oven-sh / bun

Incredibly fast JavaScript runtime, bundler, test runner, and package manager – all in one
https://bun.sh
Other
74.17k stars 2.77k forks source link

Unable to mock/spyOn Bun.file() #4045

Open sstur opened 1 year ago

sstur commented 1 year ago

What version of Bun is running?

0.7.3

What platform is your computer?

Darwin 22.2.0 arm64 arm

What steps can reproduce the bug?

spyOn(Bun, 'file').mockImplementation(() => {
  return (filePath) => {
    return { _mock: filePath } as any;
  };
});

Runtime error:

error: spyOn(target, prop) does not support accessor properties yet

What is the expected behavior?

spyOn(...).mockImplementation() should work on Bun.file as it would with other objects.

What do you see instead?

error: spyOn(target, prop) does not support accessor properties yet

Additional information

Currently there appears to be no way to mock Bun.file(). I mentioned this in Discord and opening this issue was suggested.

IgorKrupenja commented 1 year ago

Not sure if this is a good way but I was able to mock Bun.file with:

it('should return the contents of the file as a string', async () => {
  const fileContents = 'This is the file contents.';
  const path = '/path/to/file.txt';
  const bunFileSpy = spyOn(Bun, 'file').mockImplementationOnce(
    mock((_: string) => {
      return {
        text: () => Promise.resolve(fileContents),
      };
    }) as Mock<AnyFunction>
  );

  expect(await getArticleFileString(path)).toEqual(fileContents);
  expect(bunFileSpy.mock.calls[0]).toEqual([path]);
});