无法使用Jest + React模拟console.error

时间:2017-01-27 18:55:59

标签: reactjs mocking jestjs enzyme

如何模拟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();
  });
});

给我以下错误

● <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)

环境信息:

  • 反应15.2.1
  • jest 17.0.3
  • 酶2.4.1

更新

我想这是一个重复的问题。以下是我使用其他Stackoverflow帖子解决问题的方法

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

0 个答案:

没有答案
相关问题