Andreas Nordén
Andreas Nordén

Reputation: 21

Unit test non static methods in React

I want to write unit tests for methods in a react component. I want to do this without render the component. This because I do not want to set up all the data needed for a full render. I want to do something like this:

describe('MyList', function () {
  describe('fooSort', function () {
     it('sort strings', function () {
      var list = <MyList />;

      var result = list.fooSort(['a', 'c', 'b'])
      expect(result).to.be.equal(['a', 'b', 'c'])
    });
  });
});

This can be achieved by adding fooSort as a static method, but that will make it impossible for the method to access this. And it also does not feel right.

Is there a way to access the methods or is it an other way to do this kind of testing?

I know this post is similar to: How do I access methods in React for unit testing but not really the same.

Upvotes: 2

Views: 624

Answers (1)

Albert Still
Albert Still

Reputation: 1009

If you use new MyList instead of JSX <MyList /> this would work.

describe('MyList', function () {
  describe('fooSort', function () {
     it('sort strings', function () {
      var list = new MyList;

      var result = list.fooSort(['a', 'c', 'b'])
      expect(result).to.be.equal(['a', 'b', 'c'])
    });
  });
});

Note being if it's JSX it will be transpiled to React.createElement(MyList) which in your case is not what you want.

Upvotes: 1

Related Questions