[英]How do I properly test a function that use axios.get and cheerios.load functions with mocha and chai?
I have this index.js file我有这个 index.js 文件
const axios = require("axios");
const cheerio = require('cheerio');
const fetchData = async (webpage) => {
const result = await axios.get(webpage);
return cheerio.load(result.data);
}
const extractData = async (webPage) => {
const $ = await fetchData(webPage);
const numMains = $('.rank').text();
//Should return the following string
//1.2.3.4.5.6.7.8.9.10.11.12.13.14.15.16.17.18.19.20.21.22.23.24.25.26.27.28.29.30.
return numMains;
}
const siteUrl = "https://news.ycombinator.com/";
(async (webPage) => {console.log(await extractData(webPage));})(siteUrl);
module.exports = {
extractData: extractData
}
And I have this test.js file我有这个 test.js 文件
var chai = require('chai');
var expect = chai.expect;
var functionNames = require('../index.js');
describe('extractData() Unit-Test', () => {
it('This function should return a given string', () => {
// 1. ARRANGE
const siteUrl = "https://news.ycombinator.com/";
const shouldResult = "1.2.3.4.5.6.7.8.9.10.11.12.13.14.15.16.17.18.19.20.21.22.23.24.25.26.27.28.29.30.";
// 2. ACT
const result = functionNames.extractData(siteUrl);
// 3. ASSERT
expect(result).to.be.equal(shouldResult);
});
});
*I'm not getting pass with this AssertionError: * *我没有通过这个 AssertionError:*
AssertionError: expected {} to equal '1.2.3.4.5.6.7.8.9.10.11.12.13.14.15.16.17.18.19.20.21.22.23.24.25.26.27.28.29.30.'
Does someone know what I'm doing wrong and how can I solve this problem?有人知道我做错了什么,我该如何解决这个问题?
You're missing an await
, you're comparing a Promise
against 1,2,3
...你错过了await
,你正在比较Promise
和1,2,3
...
it('This function should return a given string', async() => {
// 1. ARRANGE
const siteUrl = "https://news.ycombinator.com/";
const shouldResult = "1.2.3.4.5.6.7.8.9.10.11.12.13.14.15.16.17.18.19.20.21.22.23.24.25.26.27.28.29.30.";
// 2. ACT
const result = await functionNames.extractData(siteUrl);
// 3. ASSERT
expect(result).to.be.equal(shouldResult);
});
Have in mind that you're actually performing the request while doing the test, if the site is down the test will fail.请记住,您实际上是在进行测试时执行请求,如果站点关闭,则测试将失败。 If you don't want that you can mock the request, using nock
or a similar package.如果您不想这样,您可以使用nock
或类似的 package 模拟请求。
As an alternative to Marcos's solution, you could also use eventually
from chai:作为 Marcos 解决方案的替代方案,您还可以eventually
从 chai 使用:
result.should.eventually.equal(shouldResult);
Documentation here: https://www.chaijs.com/plugins/chai-as-promised/此处的文档: https://www.chaijs.com/plugins/chai-as-promised/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.