为什么 fetchmock 恢复会给出无与伦比的获取?

问题描述 投票:0回答:1

我已经根据已经定义的测试用例编写了逻辑。基本上,下面的 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)
javascript fetch-api karma-mocha fetch-mock
1个回答
0
投票

在此测试用例中,fetchMock 正在检查该函数是否只有一个 API 调用。

“addFavourites() 中只能有一个服务器调用”

因此您只能进行一次 API 调用,那就是

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

因此,不应在此

addFavourite(id)
函数内进行以下 API 调用。

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

实现此要求的一种方法是拥有一个数组,并在此函数之外进行 API 调用后将电影和收藏夹列表存储在其中。

测试用例:

fetchMock.restore();
行之后 fetchMock 重置其内存并检查一个 API 调用,因为测试用例内没有任何其他 API 调用,直到
expect(fetchMock.done()).to.equal(true); done();
部分已执行。

© www.soinside.com 2019 - 2024. All rights reserved.