Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mock Response.headers.get()

I have a method which extracts the fileName from a http response header:

export const getFilenameFromResponse = response => {
 const filenameRegex = /filename[^=\n]*=["](.*?)["]/;
 const matches = filenameRegex.exec(
   response.headers.get('Content-Disposition')
 );
 return matches != null && matches[1] ? matches[1] : '';
}; 

Now I was going to write a unit test with Jest. Unfortunately, In cannot do something like

const headers = myHeaders = new Headers([
    ['Content-Disposition', 'form-data; fileName="testfile.txt"']
]);
const response = new Response ({headers: newHeaders});
result = getFilenameFromResponse(response)
expect(result).ToEqual('testfile.txt';

because the test fails because the result ist an empty string. I guess, it is due to wrong init of the response object.

Is there a way to mock response.headers.get()?

like image 728
Jominho Avatar asked Aug 05 '26 10:08

Jominho


1 Answers

You could use spyOn to set the behaviour of the get function:

const response = new Response ({headers: newHeaders});
const get = jest.spyOn(response.headers, 'get')
get.mockImplementation(()=> '')// do what ever `get` should to

The other way would be not create a real Response but just pass in a plain object:

const response = {
  headers: {
    get: jest.fn(()=> '')// do what ever `get` should to )
  }
}
like image 91
Andreas Köberle Avatar answered Aug 08 '26 00:08

Andreas Köberle



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!