如何在测试期间从组件中访问refs
?我尝试过使用TestUtils.renderIntoDocument
(la http://myshareoftech.com/2013/12/unit-testing-react-dot-js-with-jasmine-and-karma.html)和TestUtils.createRenderer().render()
,但在这两种情况下,我的组件refs
似乎都未定义(正在运行) PhantomJS和Chrome中的Jasmine / Karma)。我有什么遗失的吗?
我的假设是,这可能是由于0.14的变化导致分裂ReactDOM,但我无法验证。
这是我的代码:
import React from 'react'; // v0.14
import TestUtils from 'react/lib/ReactTestUtils';
import SeatList from '../../client/seat-list';
describe('SeatList', () => {
// using ReactShallowRenderer
var renderer = TestUtils.createRenderer();
function getRenderedResult(props = {}) {
renderer.render(<SeatList playerColor={props.playerColor || null}
white={props.white || undefined}
black={props.black || undefined}
sitOrStandAs={props.sitOrStandAs || null} />);
return renderer.getRenderOutput();
}
it('allows a user to sit in an open seat', () => {
let sitOrStandAs = jasmine.createSpy('sitOrStandAs');
let result = getRenderedResult({sitOrStandAs: sitOrStandAs});
console.log(result.refs); // result.refs is undefined :(
// using TestUtils.renderIntoDocument
let seatList = <SeatList playerColor={null} white={undefined} black={undefined} sitOrStandAs={sitOrStandAs} />;
TestUtils.renderIntoDocument(seatList);
let btn = seatList.refs.white; // throws Exception: seatList.refs is undefined :(
TestUtils.Simulate.click(btn);
expect(sitOrStandAs).toHaveBeenCalled();
});
});
任何建议都会很棒。谢谢!
答案 0 :(得分:0)
我的错误印象是renderIntoDocument
没有回复任何有用的东西。正确的解决方案是将seatList分配给TestUtils.renderIntoDocument
的返回值:
let seatList = TestUtils.renderIntoDocument(seatList);
在此之后,测试通过,我现在感到更快乐。