Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/unit-testing/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 用jest测试回调函数_Javascript_Unit Testing_Callback_Jestjs_Puppeteer - Fatal编程技术网

Javascript 用jest测试回调函数

Javascript 用jest测试回调函数,javascript,unit-testing,callback,jestjs,puppeteer,Javascript,Unit Testing,Callback,Jestjs,Puppeteer,我试图测试一个内部有回调的函数。我设置了一个模拟函数,但我还需要测试回调 我试着将它作为另一个模拟函数分开,但它不算作覆盖 我正在尝试测试的功能: export const checkDescription = async page => { const metaDescription = await page.$eval( 'meta[name="description"]', description => description.getAttrib

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

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

我正在尝试测试的功能:

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中包含描述的正确方法。

你接近了

description
箭头函数被传递到您的
页面。$eval
模拟函数,以便您可以使用它来检索它

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

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
});
test(“应该返回描述”,async()=>{
expect(等待checkDescription(page)).toBe(“Value”);//成功!
期望(page.$eval).tohavebeencall();//成功!
const description=page.$eval.mock.calls[0][1];//“mock content”);
expect(description({getAttribute:getAttributeMock})).toBe('mock content');//成功!
expect(getAttributeMock).toHaveBeenCalledWith('content');//成功!
//成功!checkDescription现在已完全覆盖代码
});

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