1

How does one mock console.error?

import React from 'react';
import { shallow } from 'enzyme';
import Button from '../Button';

describe('<Button>', () => {
  it('should fail proptype validation if the autoWidthGroupId contains anything but letters and numbers', () => {
    const myMock = jest.fn();
    console.error = new myMock();
    shallow(<Button autoWidthGroupId={'bad id'}>Hello</Button>);
    expect(myMock).toBeCalled();
  });
});

Gives me the following error

● <Button> › should fail proptype validation if the autoWidthGroupId contains anything but letters and numbers

TypeError: console.error is not a function

  at printWarning (node_modules/fbjs/lib/warning.js:36:17)
  at warning (node_modules/fbjs/lib/warning.js:60:22)
  at checkReactTypeSpec (node_modules/react/lib/checkReactTypeSpec.js:80:49)
  at validatePropTypes (node_modules/react/lib/ReactElementValidator.js:151:5)
  at Object.ReactElementValidator.createElement (node_modules/react/lib/ReactElementValidator.js:194:5)
  at Object.<anonymous> (src/Button/__tests__/Button.test.jsx:53:60)

Environment info:

  • react 15.2.1
  • jest 17.0.3
  • enzyme 2.4.1

UPDATE

This is a duplicate question, I guess. Here is how I solved the issue using the other Stackoverflow post

  it('should fail proptype validation if the autoWidthGroupId contains anything but letters and numbers', () => {
    const myMock = jest.fn();
    global.console = { error: myMock };
    shallow(<Button autoWidthGroupId={'bad id'}>Hello</Button>);
    expect(myMock).toBeCalled();
  });
Canta
  • 1,480
  • 1
  • 13
  • 26
mrbinky3000
  • 4,055
  • 8
  • 43
  • 54

0 Answers0