mercredi 30 mars 2016

When testing a React component, is there any way to directly call its non-lifecycle methods?

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 = TestUtils.renderIntoDocument(
      <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?

Aucun commentaire:

Enregistrer un commentaire