Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use Fetch-Mock to return test Blob

I have a fetch which receives a file from a server and I am trying to mock the fetch for my tests with fetch-mock.
Using this code I can mock the endpoint and place the blob in the body:

const blob = new Blob(['a', 'b', 'c', 'd']);
fetchMock.once('*', {body: blob}, {sendAsJson: false});

The code that is being tested is:

fetch(url).then( ( response ) => {
            console.log(response);
            return response.blob();
        } ).then( ( blob ) => {
            console.log(blob);
        } )

I can see that the Blob is on the body of the request

Body {
    url: '/mock/url',
    status: 200,
    statusText: 'OK',
    headers: Headers { _headers: {} },
    ok: true,
    body: Blob {},
    bodyUsed: false,
    size: 0,
    timeout: 0,
    _raw: [],
    _abort: false }

But running the test throws the error:

    TypeError: response.blob is not a function

Running the code with a server returns a valid Blob into the final .then.

like image 585
HauptmannEck Avatar asked Oct 10 '18 20:10

HauptmannEck


1 Answers

So the solution was that fetch-mock has a peer dependency on node-fetch which is used during the jest tests. I had an older version of node-fetch pulled in by another library.

So directly requiring the latest node-fetch in my package.json solved this issue.

like image 132
HauptmannEck Avatar answered Nov 18 '22 14:11

HauptmannEck