使用Jest测试回调函数

19

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

我试图将其分离为另一个模拟函数,但它不算在覆盖范围内。

我正在尝试测试的函数:

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内部覆盖描述的方式是不正确的。


调用该函数是否会产生任何副作用,你能观察到吗?它实现了什么行为? - jonrsharpe
它返回一个页面描述作为字符串。 - Elena
2个回答

12

你离成功不远了!

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
});

1

我通过回调函数从串口接收异步消息。请在此处查看详细信息: https://jest-bot.github.io/jest/docs/asynchronous.html

import { InpassTerminal } from "../src/main.js"

jest.setTimeout(45000);
describe('Basic tests', () => {
test('1. Host connection', async (done) => {     
    await new Promise( resolve => setTimeout(resolve, 500) ); 

    const commandTest = {actionCode: '12345', terminalId: '1019****'}

    function cb (data) { 
      if (data.operationCode == 12345) {
        const actualStatus = Buffer.from(data.status, "ascii")          
        const expectedStatus = '1'

        expect(actualStatus.toString()).toBe(expectedStatus)      
        done()
      }
    }  
    const terminal = new InpasTerminal()
    terminal.exec('/dev/ttyPos0', commandTest, cb)
})

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接