摩卡&酶 - 同样的测试第二次失败

时间:2017-05-19 14:31:25

标签: reactjs mocha chai enzyme chai-enzyme

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

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

知道为什么吗?

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

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

0 个答案:

没有答案
相关问题