почему восстановление fetchmock дает непревзойденный get? - PullRequest
2 голосов
/ 04 июня 2019

Я написал логику на основе уже определенных тестовых случаев. В основном, tc проверяет один серверный вызов ниже, это код. Как мне изменить мою логику, чтобы tc прошел?

это тестовый пример:

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();
        });
});

это логика написана. Он в основном делает вызов фильмов, пытается получить его, проверяет, существует ли выбранный фаворит, и добавляет, если его нет

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));
    });

}

ошибка:

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)
...