【问题标题】:Test callback function with jest用 jest 测试回调函数
【发布时间】:2019-09-21 08:10:00
【问题描述】:

我正在尝试测试一个内部带有回调的函数。我设置了一个模拟函数,但我还需要测试一个回调。

我尝试将它作为另一个模拟函数分开,但它不算作覆盖。

我正在尝试测试的功能:

export const checkDescription = async page => {
    const metaDescription = await page.$eval(
      'meta[name="description"]',
      description => description.getAttribute("content")
    );
    return metaDescription;
};

我已经模拟了页面功能:

const page = {
  $eval: jest.fn(() => "Value")
};

我的测试:

test("Should return description", async () => {
  expect(await checkDescription(page)).toBe("Value"); 
  expect(page.$eval).toHaveBeenCalled();
});

我试过分开描述:

const description = {
  getAttribute: jest.fn(() => "Value")
};  

但我认为这不是在 $eval 中包含描述的正确方法。

【问题讨论】:

  • 调用该函数是否有任何您可以观察到的副作用?它实现的行为是什么?
  • 它以字符串形式返回页面描述

标签: javascript unit-testing callback jestjs puppeteer


【解决方案1】:

你已经接近了!

description 箭头函数被传递给您的 page.$eval 模拟函数,因此您可以使用 mockFn.mock.calls 来检索它。

一旦你检索到它,你可以直接调用它来测试它并获得完整的代码覆盖率:

test("Should return description", async () => {
  expect(await checkDescription(page)).toBe("Value");  // Success!
  expect(page.$eval).toHaveBeenCalled();  // Success!

  const description = page.$eval.mock.calls[0][1];  // <= get the description arrow function
  const getAttributeMock = jest.fn(() => 'mock content');
  expect(description({ getAttribute: getAttributeMock })).toBe('mock content');  // Success!
  expect(getAttributeMock).toHaveBeenCalledWith('content');  // Success!
  // Success!  checkDescription now has full code coverage
});

【讨论】:

    猜你喜欢
    • 2021-08-08
    • 2022-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-25
    • 2018-01-21
    • 2020-01-24
    • 2020-03-23
    相关资源
    最近更新 更多