How to test React PropTypes through Jest?

前端 未结 6 1176
终归单人心
终归单人心 2020-12-25 12:22

I\'m writing Jest tests for my React code and hoping to make use of/test the PropType checks. I am quite new to the Javascript universe. I\'m using npm to install reac

6条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-25 12:58

    The underlying problem is How to test console.log?

    The short answer is that you should replace the console.{method} for the duration of the test. The common approach is to use spies. In this particular case, you might want to use stubs to prevent the output.

    Here is an example implementation using Sinon.js (Sinon.js provides standalone spies, stubs and mocks):

    import {
        expect
    } from 'chai';
    import DateName from './../../src/app/components/DateName';
    import createComponent from './create-component';
    import sinon from 'sinon';
    
    describe('DateName', () => {
        it('throws an error if date input does not represent 12:00:00 AM UTC', () => {
            let stub;
    
            stub = sinon.stub(console, 'error');
    
            createComponent(DateName, {date: 1470009600000});
    
            expect(stub.calledOnce).to.equal(true);
            expect(stub.calledWithExactly('Warning: Failed propType: Date unix timestamp must represent 00:00:00 (HH:mm:ss) time.')).to.equal(true);
    
            console.error.restore();
        });
    });
    

    In this example DataName component will throw an error when initialised with a timestamp value that does not represent a precise date (12:00:00 AM).

    I am stubbing the console.error method (This is what Facebook warning module is using internally to generate the error). I ensure that the stub has been called once and with exactly one parameter representing the error.

提交回复
热议问题