Untitled

 avatar
unknown
typescript
3 years ago
2.2 kB
4
Indexable

I am using mock-service-worker


rest.get<DefaultRequestBody, PathParams, Buffer>('/uploads/*', (req, res, ctx) => {
const imageBuffer = readFileSync(resolve(__dirname, '../fixtures/image.jpg'));

return res(
  ctx.status(200),
  ctx.set('Content-Length', imageBuffer.byteLength.toString()),
  ctx.set('Content-Type', 'image/jpeg'),
  ctx.body(imageBuffer)
);
}),


to mock this function that downloads image


export const getImage = async (url: string): Promise<File> => {
  const response = await axiosInstance.get(url, { responseType: 'blob' });
  const file = new File([response.data], 'default-image'); // here, this constructor just gives {} always
  return file;
};


`getImage()` is then called in react-hook-form to load image asynchronously into the form via Dropzone


const runHeader = async (user: ClientUser) => {
  const headerUrl = getHeaderImagePath(user);
  const header = await getImage(headerUrl); // here

  reset({
	...getValues(),
	header,
  } as SettingsFormData);
  setIsHeaderLoading(false);
};


then Dropzone displays that image using `URL.createObjectURL()`


<img
	src={URL.createObjectURL(file)} // here
	alt={altText}
	className={b('image') + ` ${imageClassName}`}
/>


then inside the test file I asert that img tag has `src` attribute in format `blob:https://site.com/uplads/headers/image.jpg`


// assert header image - async
const headerImage = await screen.findByRole('img', { name: /header\-image/i });
expect(headerImage).toBeInTheDocument();
expect(headerImage).toHaveAttribute(
  'href',
  expect.stringMatching(/^blob:https?:\/\//i)
);


mock-service-worker mock works fine and returns binary data, main problem is in File constructor which in jsdom always returns just empty object `{}`, this line `const file = new File([response.data], 'default-image');`, so I need to mock it in global namespace, but I cant find single example on Google how to do it.

I also plan to mock `URL.createObjectURL` just to forward image url to the src attribute.


Object.defineProperty(window.URL, 'createObjectURL', {
  value: jest.fn().mockImplementation((arg) => arg),
});


Do you know where I can find complete type safe example how to mock `File` constructor in jsdom?