0

我正在尝试使用一些 propType 逻辑测试一个 React 组件。该组件应采用myprop应该匹配的道具{value: [anything]}

第一个测试有效,但第二个(完全相同的代码)没有。

知道为什么吗?

编辑:我认为 React 不是console.error()每次都调用,而是只调用一次。可能是为了避免向控制台发送垃圾邮件......

import React from 'react';
import chai, { expect } from 'chai';
import chaiEnzyme from 'chai-enzyme'
import { shallow } from 'enzyme';
chai.use(chaiEnzyme());

class MyComponent extends React.Component {
    render() {
        return (
            <div>
                {this.props.myprop.value}
            </div>
        );
    }
}
MyComponent.propTypes = {
    myprop: (props, propName, componentName) => {
        const prop = props[propName];
        if (typeof(prop) !== 'object') {
            return new Error(`<${componentName}> requires the prop \`${propName}\``);
        }
        else {
            if (typeof(prop.error) === 'undefined' || !prop.error) {
                if (typeof(prop.value) === 'undefined') {
                    return new Error(`<${componentName}> requires the prop \`${propName}\` to have a \`value\` field`);
                }
            }
        }
        return null;
    },
};

//Mocking console.error to throw propType errors
let console_error = console.error;
console.error = function(warning) {
    if (/(Invalid prop|Failed prop type)/.test(warning)) {
        throw new Error(warning);
    }
    console_error.apply(console, arguments);
};

describe('<MyComponent/>', function() {
    describe('with invalid `myprop` format', function() {
        it('should throw an error', function(done) {
            //This test passes

            //Execute
            const fn = () => shallow(<MyComponent myprop={{}}/>);

            //Verify
            expect(fn).to.throw(Error, 'requires the prop \`myprop\` to have a \`value\` field');
            done();
        });

        it('should throw an error', function(done) {
            //Exactly the same code as above -- does not pass

            //Execute
            const fn = () => shallow(<MyComponent myprop={{}}/>);

            //Verify
            expect(fn).to.throw(Error, 'requires the prop \`myprop\` to have a \`value\` field');
            done();
        });
    });
});
4

0 回答 0