why does fetchmock restore give unmatched get?
Asked Answered
M

1

7

I have written logic based on test cases already defined.Basically the tc checks for one server call below is the code.How do I modify my logic to make the tc pass?

this is test case:

it('there shall be only one server call in addFavourites()', (done) => {
        fetchMock.get('http://localhost:3000/movies', moviesTestData);
        fetchMock.get('http://localhost:3000/favourites', favouritesTestData);

        script.getMovies()
        .then(() => {
            return script.getFavourites();
        })
        .then(() => {
            fetchMock.restore();
            fetchMock.post('http://localhost:3000/favourites', moviesTestData[1]);
            return script.addFavourite(27621);
        })
        .then(() => {
             expect(fetchMock.done()).to.equal(true);
             done();
        })
        .catch((err) => {
            expect(err).to.equal(null, err);
            done();
        });
});

this is the logic written.It basically makes call to movies,tries to get it,checks if the selected favourite exists and adds if its not there

function addFavourite(event) {
    const id = event;
    // eslint-disable-next-line consistent-this
    // const self = this;
    let favmovie = {};
    let favmovies={};
    //     let favmovie = {};
     return fetch('http://localhost:3000/movies')
    .then(response =>{

        if(response.status === 200)
        {
             return Promise.resolve(response.json());
        }
        else
        // eslint-disable-next-line no-else-return
        {
         return Promise.reject(new Error('Unable to fetch the data'));
        }
    }).then(movies=>{
        console.log('moviesssss',movies);
        movies.forEach(movie => {
            if(movie.id === id) {
             favmovie = movie;
            }
        return Promise.resolve(favmovie);
    })
    return fetch('http://localhost:3000/favourites')
    .then(response =>{
        if(response.status === 200)
        {
             return Promise.resolve(response.json());
        }
        else
        // eslint-disable-next-line no-else-return
        {
         return Promise.reject(new Error('Unable to fetch the data'));
        }
    });

}).then(favmoves=>{
      favmovies = favmoves;
      }).then(()=>{
        favmovies.filter(function(movie) {  
        if(movie.id === id) {
        // eslint-disable-next-line no-alert
        alert('Movie is already added to favourites');
        }
        }); 
    }).then(()=>{
        return fetch('http://localhost:3000/favourites', {
            method: 'POST',
            body: JSON.stringify( favmovie),
            headers: {
                'content-type': 'application/json'
            }
        })
        .then(addedFav =>{
            // console.log('addedFav',addedFav.json());
             return Promise.resolve(addedFav.json());
     }).then(resp=>{
        const ul = document.getElementById('favouritesList');
        const div = document.createElement('div');
        const img = document.createElement('img');
        img.setAttribute('src', resp.posterPath);
        div.classList.add('moviecontent');
        img.classList.add('image');
        div.appendChild(document.createTextNode(resp.title));
        div.appendChild(img);
        div.appendChild(document.createTextNode(resp.overview));
        ul.appendChild(div);
        console.log('resp',resp);
     });
    }).catch(err =>{
        return Promise.reject(new Error(null, err));
    });

}

error is :

Unmatched GET to http://localhost:3000/movies
(node:59340) UnhandledPromiseRejectionWarning: AssertionError: Error: No fallback response defined for GET to http://localhost:3000/movies: expected [Error: No fallback response defined for GET to http://localhost:3000/movies] to equal null
    at /Users/anushamuthyalampally/Stack Route/Assignment/javascript-movie-cruiser-assignment/test/script.spec.js:230:20
(node:59340) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:59340) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
    1) there shall be only one server call in addFavourites()


  0 passing (2s)
  1 failing

  1) Movie Cruiser

     there shall be only one server call in addFavourites():
     Error: Timeout of 2000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves. (/Users/anushamuthyalampally/Stack Route/Assignment/javascript-movie-cruiser-assignment/test/script.spec.js)
      at listOnTimeout (internal/timers.js:531:17)
      at processTimers (internal/timers.js:475:7)
Malpighiaceous answered 4/6, 2019 at 1:16 Comment(1)
Any solution to this, even i also got the same issue ?Cognate
D
0

In this test case fetchMock is checking whether the function has only one API call.

'there shall be only one server call in addFavourites()'

Therefore you can have only one API call and that is

fetch('http://localhost:3000/favourites', {
            method: 'POST',
            body: JSON.stringify( favmovie),
            headers: {
                'content-type': 'application/json'
            }
        })

Therefore following API calls shouldn't be made inside this addFavourite(id) function.

fetch('http://localhost:3000/movies')
fetch('http://localhost:3000/favourites')

One way to implement this requirement is to have an array and to store movies and favourites lists there after those API calls being made outside of this function.

Test case: After fetchMock.restore(); line fetchMock resets its memory and checks for one API call because there are no any other API calls inside the test case until expect(fetchMock.done()).to.equal(true); done(); part is executed.

Defray answered 7/5 at 8:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.