在摩卡和柴测试承诺

时间:2018-08-29 21:29:38

标签: javascript express promise mocha chai

export class YoutubeService {
  getTrendingVideos(country) {
    var params = {
      part: 'snippet',
      chart: 'mostPopular',
      regionCode: country, // should be replaced with country code from countryList
      maxResults: '24',
      key: config.youtubeApi.key
    };
    let result = [];
    let promises = [];
    return axios.get('/', {params}).then(function(res){
      result = res.data.items;
      for (var i = 0; i < result.length; i++) {
          result[i] = {
              id: result[i].id,
              title: result[i].snippet.title,
              thumbnail: result[i].snippet.thumbnails.high.url,
              publishedAt: moment(result[i].snippet.publishedAt).fromNow()
          };
          promises.push(YoutubeService.getVideoDetails(result[i]));
      }
      return Promise.all(promises);
    });
  }

  static getVideoDetails(video) {
    let params = {
      part: 'statistics',
      id: video.id,
      key: config.youtubeApi.key
    };

    return axios.get('/', {params}).then(function(res) {
      let result = res.data;
      video.viewCount = result['items'][0].statistics.viewCount;
      video.likeCount = result['items'][0].statistics.likeCount;
      return video;
    });
  }
}

我不知道如何使用摩卡和柴进行测试,尤其是诺言。如何使用chai断言测试这两个函数。 我应该如何对这两个功能进行单元测试 预先感谢。

2 个答案:

答案 0 :(得分:0)

您将向it发送一个函数,该函数将在完成解析后收到一个done函数来调用。

it('does resolve later', function(done) {
    asyncCall().then(()=>{ done(); }
})


it('does resolve later', async function(done) {
    await asyncCall()
    done()
})

您还可以返回承诺。

it('does resolve later', function () {
    return asyncCall()
})

答案 1 :(得分:0)

看看Chai as Promised库,它提供了可链接的argc,可帮助删除一些期望异步解析的样板:

eventually