Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Mock File constructor?#449

Unanswered
nemanjam asked this question inQ&A
Discussion options

I am using mock-service-worker

rest.get<DefaultRequestBody,PathParams,Buffer>('/uploads/*',(req,res,ctx)=>{constimageBuffer=readFileSync(resolve(__dirname,'../fixtures/image.jpg'));returnres(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

exportconstgetImage=async(url:string):Promise<File>=>{constresponse=awaitaxiosInstance.get(url,{responseType:'blob'});constfile=newFile([response.data],'default-image');// here, this constructor just gives {} alwaysreturnfile;};

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

construnHeader=async(user:ClientUser)=>{constheaderUrl=getHeaderImagePath(user);constheader=awaitgetImage(headerUrl);// herereset({...getValues(),header,}asSettingsFormData);setIsHeaderLoading(false);};

then Dropzone displays that image usingURL.createObjectURL()

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

then inside the test file I asert that img tag hassrc attribute in formatblob:https://site.com/uplads/headers/image.jpg

// assert header image - asyncconstheaderImage=awaitscreen.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 lineconst 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 mockURL.createObjectURL just to forward image url to the src attribute.

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

Jest environment is:

testEnvironment:'jsdom',

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

You must be logged in to vote

Replies: 1 comment

Comment options

This looks like something that you should be asking about in jsdom. It's not related to jest-dom, is it?

You must be logged in to vote
0 replies
Sign up for freeto join this conversation on GitHub. Already have an account?Sign in to comment
Category
Q&A
Labels
None yet
2 participants
@nemanjam@gnapse

[8]ページ先頭

©2009-2025 Movatter.jp