简体   繁体   English

用笑话测试回调 function

[英]Test callback function with jest

I'm trying to test a function with a callback inside.我正在尝试使用内部回调测试 function。 I set up a mock function, but I also need to test a callback.我设置了一个模拟 function,但我还需要测试一个回调。

I've tried to separate it as another mock function, but it doesn't counted as covered.我试图将它作为另一个模拟 function 分开,但它不算作涵盖。

Function I'm trying to test: Function 我正在尝试测试:

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

I've mocked the page function:我嘲笑了页面 function:

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

my test:我的测试:

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

I've tried to separate description:我试图分开描述:

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

but I don't think that it's a correct way to cover description inside $eval.但我不认为这是在 $eval 中覆盖描述的正确方法。

You're close! 你近了!

The description arrow function is passed to your page.$eval mock function so you can use mockFn.mock.calls to retrieve it. description箭头函数将传递到您的page.$eval模拟函数,以便您可以使用mockFn.mock.calls进行检索。

Once you've retrieved it, you can call it directly to test it and get full code coverage: 检索到它之后,可以直接调用它进行测试并获得完整的代码覆盖:

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

I receive async messages from serial port via callbacks.我通过回调从串行端口接收异步消息。 Try to read here: https://jest-bot.github.io/jest/docs/asynchronous.html试着在这里阅读: 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)
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM