JEST期望在setTimeout中调用toBeCalled函数

时间:2018-11-07 10:58:37

标签: javascript unit-testing jestjs

我有一个简单的函数,它可以在setTimeout中打开一个新窗口,并希望测试是否已打开该窗口。

try{
  String imgName="C:\\Users\\pc\\Desktop\\Pictures\\neosphere.png";
  BufferedImage bImage = ImageIO.read(new File(imgName));//give the path of an image
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ImageIO.write( bImage, "png", baos );
    baos.flush();
    byte[] imageInByteArray = baos.toByteArray();
    baos.close();                                   
    String b64 = DatatypeConverter.printBase64Binary(imageInByteArray);
    %>
    <img style="height:90px" align="center" class="img-responsive" src="data:image/jpg;base64, <%=b64%>" alt="Missing Picture"/>                            
    <% 
}catch(IOException e){
  System.out.println("Error: "+e);
} 


%>

目前,我的期望因“预期的模拟函数已被调用”而失败。当我从函数中删除setTimeout时,随着测试通过,window.open的模拟看起来可以正常工作。

只是想知道是否有人可以引导我朝着正确的方向前进。预先感谢。

2 个答案:

答案 0 :(得分:0)

您可以模拟global.open并检查其在执行foo()时是否被调用:

it('calls open', (done) => {
        global.open = jest.fn(); // mocking global.open
        foo();  // calling foo()

        setTimeout(()=> {
          expect(global.open).toBeCalled()
          done()
        })
})

答案 1 :(得分:0)

根据https://jestjs.io/docs/en/timer-mocks上的文档,不仅应该伪造计时器,还应使用jest.runAllTimers();来运行计时器,如下例所示:

test('calls the callback after 1 second', () => {
  const timerGame = require('../timerGame');
  const callback = jest.fn();
  jest.useFakeTimers();

  timerGame(callback);

  // At this point in time, the callback should not have been called yet
  expect(callback).not.toBeCalled();

  // Fast-forward until all timers have been executed
  jest.runAllTimers();

  // Now our callback should have been called!
  expect(callback).toBeCalled();
  expect(callback).toHaveBeenCalledTimes(1);
});