首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如果返回值是对象数组,如何编写通过的jest测试?

如果返回值是对象数组,如何编写通过的jest测试?
EN

Stack Overflow用户
提问于 2021-02-23 18:57:52
回答 1查看 86关注 0票数 0

我正在学习单元测试,并且我已经涵盖了大部分基础知识。

现在我正试着测试我的刮刀。我的初始函数涉及多个刮板,但我想检查每个刮板是否都能正常工作。测试的输出(为了测试成功)应该是如果返回有一个对象的[{},{},...,{}]数组。我真的不知道对象的内部是什么(数据总是不同的),但它总是一个对象数组。

现在我的问题是:如何正确地做到这一点?我尝试过多种方法,但我的测试总是失败。下面是我一直以来的解决方案:

代码语言:javascript
复制
const santScraper = require('../scraping/scrapers/sant-scraper');

test('Does scraper works properly', async () => {
  await expect(santScraper(1)).toBe({});
});

但我的输出是:

代码语言:javascript
复制
FAIL  tests/santScraper.test.js
  × Does scraper works properly (20 ms)

  ● Does scraper works properly

    expect(received).toBe(expected) // Object.is equality

    - Expected  - 1
    + Received  + 1

    - Object {}
    + Promise {}

      2 |
      3 | test('Does scraper works properly', async () => {
    > 4 |   await expect(santScraper(1)).toBe({});
        |                                ^
      5 | });
      6 |

      at Object.<anonymous> (tests/santScraper.test.js:4:32)

Test Suites: 1 failed, 1 total
Tests:       1 failed, 1 total
Snapshots:   0 total
Time:        2.016 s
Ran all test suites.
npm ERR! Test failed.  See above for more details.

我真的不知道它指的是什么。

这也是我的刮刀:

代码语言:javascript
复制
//const data_functions = require('../data-functions/data-functions');
const axios = require('axios'); //npm package - promise based http client
const cheerio = require('cheerio'); //npm package - used for web-scraping in server-side implementations
const data_functions = require('../data-functions/data-functions');

//santScaper function which as paramater needs count which is sent in the scraping-service file.
const santScraper = async (count) => {
  const url = `https://www.sant.ba/pretraga/prodaja-1/tip-2/cijena_min-20000/stranica-${count}`;

  const santScrapedData = [];
  try {
    await load_url(url, santScrapedData);
  } catch (error) {
    console.log(error);
  }
};

//Function that does loading URL part of the scraper, and starting of process for fetching raw data.
const load_url = async (url, santScrapedData) => {
  await axios.get(url).then((response) => {
    const $ = cheerio.load(response.data);
    get_article_html_nodes($).each((index, element) => {
      process_single_article($, index, element, santScrapedData);
    });

    data_functions.mergeData(santScrapedData);
    return santScrapedData; //this is where I return array of objects
  });
};

// Part where raw html data is fetched but in div that we want.
const get_article_html_nodes = ($) => {
  return $('div[class="col-xxs-12 col-xss-6 col-xs-6 col-sm-6 col-lg-4"]');
};

//Here is all logic for getting data that we want, from the raw html.
const process_single_article = ($, index, element, santScrapedData) => {
  const getLink = $(element).find('a[class="re-image"]').attr('href');
  const getDescription = $(element).find('a[class="title"]').text();
  const getPrice = $(element)
    .find('div[class="prices"] > h3[class="price"]')
    .text()
    .replace(/\.| ?KM$/g, '')
    .replace(',', '.');
  const getPicture = $(element).find('img').attr('data-original');
  const getSquaremeters = $(element)
    .find('span[class="infoCount"]')
    .first()
    .text()
    .replace(',', '.')
    .split('m')[0];
  const pricepersquaremeter =
    parseFloat(getPrice) / parseFloat(getSquaremeters);

  santScrapedData[index] = {
    id: getLink.substring(42, 46),
    link: getLink,
    description: getDescription,
    price: Math.round(getPrice),
    picture: getPicture,
    squaremeters: Math.round(getSquaremeters),
    pricepersquaremeter: Math.round(pricepersquaremeter),
  };
};

module.exports = santScraper;
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-02-23 19:01:22

在这种情况下,您可以像这样使用typeof :-

代码语言:javascript
复制
test('Does scraper works properly', async () => {
  await expect(typeof santScraper(1)).toBe('object');
});

尽管如果它总是您想要检查的Promise对象,您可以使用instanceof获得更具体的内容,如下所示:-

代码语言:javascript
复制
test('Does scraper works properly', async () => {
  await expect(santScraper(1) instanceof Promise).toBe(true);
});
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66331808

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档