Jest: how to mock console when it is used by a third-party-library?

后端 未结 2 1756
长发绾君心
长发绾君心 2020-12-08 05:49

I am trying to mock console.warn/error but i can\'t. I use a third-party-library which calls console.warn inside it. I need to test was it called or wasn\'t. In my test case

2条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-08 06:23

    You have to use global to access objects in the global context

    global.console = {warn: jest.fn()}
    expect(console.warn).toBeCalled()
    

    or use jest.spyOn added in 19.0.0

    jest.spyOn(global.console, 'warn')
    

提交回复
热议问题