如何测试cheerio js

问题描述

这是我的代码,我不知道如何为它编写测试:

html.js

const getHtml = async (url) => {
  const { data } = await axios.get(url);
  return data;
};

const cheerioInit = async (url) => cheerio.load(await getHtml(url));

module.exports = {
  cheerioInit,getHtml 
};

我想我应该嘲笑这个,但不知道该怎么做。我写了这个但出现错误

const htmlJs = require("./html");

describe("html",() => {
  it("initializes cheerio js",() => {
    const mock = jest.spyOn(htmlJs,"cheerioInit");
    expect(mock).toHaveBeenCalled();
  });
});

这是错误

enter image description here

解决方法

您可以使用 jest.spyOn(object,methodName) 模拟 axios.get() 方法及其解析值,并使用假实现模拟 cheerio.load() 方法。执行 getHtmlcheerioInit 函数后,对上述模拟进行断言以检查它们是否已使用特定参数调用。

例如

html.js

const axios = require('axios');
const cheerio = require('cheerio');

const getHtml = async (url) => {
  const { data } = await axios.get(url);
  return data;
};

const cheerioInit = async (url) => cheerio.load(await getHtml(url));

module.exports = {
  cheerioInit,getHtml,};

html.test.js

const { getHtml,cheerioInit } = require('./html');
const axios = require('axios');
const cheerio = require('cheerio');

describe('html',() => {
  afterEach(() => {
    jest.restoreAllMocks();
  });
  describe('getHtml',() => {
    it('should get html',async () => {
      const getSpy = jest.spyOn(axios,'get').mockResolvedValueOnce({ data: '<div>teresa teng</div>' });
      const actual = await getHtml('http://localhost:3000');
      expect(actual).toEqual('<div>teresa teng</div>');
      expect(getSpy).toBeCalledWith('http://localhost:3000');
    });
  });
  describe('cheerioInit',() => {
    it('should initializes cheerio',async () => {
      const loadSpy = jest.spyOn(cheerio,'load').mockImplementation();
      const getSpy = jest.spyOn(axios,'get').mockResolvedValueOnce({ data: '<div>teresa teng</div>' });
      await cheerioInit('http://localhost:3000');
      expect(loadSpy).toHaveBeenCalledWith('<div>teresa teng</div>');
    });
  });
});

单元测试结果:

 PASS  examples/66304918/html.test.js
  html
    getHtml
      ✓ should get html (3 ms)
    cheerioInit
      ✓ should initializes cheerio

----------|---------|----------|---------|---------|-------------------
File      | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
----------|---------|----------|---------|---------|-------------------
All files |     100 |      100 |     100 |     100 |                   
 html.js  |     100 |      100 |     100 |     100 |                   
----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed,1 total
Tests:       2 passed,2 total
Snapshots:   0 total
Time:        4.088 s