2

I'm using Jest, and I have some component like:

var TestClass = react.createClass({
  foo: function() {
    return "test";
  },
  render: function() {
    return <div />;
  }
});

And I want to write a unit test specifically for TestClass' foo method.

I saw that Call a React component method from outside suggested this should be possible - simply render the component in the test and call it:

describe("TestClass", function() { 
    it("should access internal methods", function() { 
    var test = <TestClass />

    expect(test.foo()).toBeTruthy()
  }
});

From that question's answer I would expect this test to pass, but instead:

test.foo is not a function

Have I misunderstood that answer?

In general I would prefer to be able to test non-lifecycle methods in this manner - it would give better granularity, but if this is not possible, is there a sane alternative?

For example how might one test a method passed as props to a component's child without this ability?

Community
  • 1
  • 1
ttrmw
  • 161
  • 1
  • 12

2 Answers2

0

Use renderIntoDocument:

import ReactTestUtils from 'react-addons-test-utils';

...

const test = ReactTestUtils.renderIntoDocument(
  <TestClass />
);
expect(test.foo()).toBeTruthy();
Anuj
  • 1,474
  • 12
  • 23
0

If you are using enzyme instead of ReactTestUtils, and you are using enzyme's mount renderer, then you can call .instance() on the ReactWrapper to retrieve the ReactComponent.

var test = mount(
  <TestClass />
);

expect(test.instance().foo()).toBeTruthy();
Zachary Ryan Smith
  • 2,688
  • 1
  • 20
  • 30