我有这个React功能性的用户界面只有组件,其中有两个道具传入,第二个是从其父组件传递的函数。 onClick调用“委托”到父容器组件中的一个函数,然后这个父方法负责调度到一个redux存储。酶/反应单元测试
import React, {Component} from 'react';
import PropTypes from 'prop-types';
const BotShowUI = ({ bot, onClick }) => {
return(
<div id={bot.id} onClick={onClick}>
{bot.id} : {bot.text}
</div>
)
}
BotShowUI.propTypes = {
bot: PropTypes.object.isRequired,
onClick: PropTypes.func.isRequired
};
export default BotShowUI;
我的测试规范是,它使用茉莉
import React, {Component} from 'react';
import { mount } from 'enzyme';
import BotShowUI from '../botShowUI';
function onClickFunction(){};
describe('botShowUI',() => {
const bot = {id: 1, isDone: false, text: 'bot 123'};
const expectedDivText = '1 : bot 123';
const wrapper = mount(<BotShowUI bot={bot} onClick={onClickFunction} />);
it(' div has been rendered ',() => {
expect(wrapper.find('div').first()).not.toBe(null);
});
it(' div displays the correct bot text ',() => {
expect(wrapper.find('div').first().text()).toEqual(expectedDivText)
});
it(' div click event fired ',() => {
wrapper.simulate('click');
expect(wrapper.state('onClick')).toBe(true);
});
});
这最后断言失败与
Chrome 57.0.2987 (Windows 10 0.0.0) botShowUI div click event fired FAILED
TypeError: Cannot read property 'onClick' of null
at ReactWrapper.state (webpack:///~/enzyme/build/ReactWrapper.js:825:24 <- tests.webpack.js:26303:25)
at Object.<anonymous> (webpack:///app/react/components/bots/_tests/botShowUI.spec.js:25:23 <- tests.webpack.js:25415:25)
wrapper.simulate('click');
作品,但下一行失败 什么是断言的正确方法点击被解雇了? 我是否必须放入包装的道具/儿童而不是使用状态?
我不想以任何方式测试父容器,两者是孤立的。 此测试仅关注此UI组件。
再一次非常感谢。我已经提出了你的答案。我已经发布了Jasmine的解决方案 – Rory