React中的单元测试非静态方法

时间:2015-02-10 13:37:31

标签: javascript unit-testing testing reactjs

我想为react组件中的方法编写单元测试。我想这样做而不渲染组件。这是因为我不想设置完整渲染所需的所有数据。我想做这样的事情:

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'])
    });
  });
});

这可以通过添加fooSort作为静态方法来实现,但这将使该方法无法访问它。它也感觉不对劲。

有没有办法访问这些方法,还是另一种方法来进行这种测试?

我知道这篇文章类似于:How do I access methods in React for unit testing但不一样。

1 个答案:

答案 0 :(得分:1)

如果您使用new MyList而不是JSX <MyList />,这将有效。

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'])
    });
  });
});

请注意,如果它是JSX,它将被转换为React.createElement(MyList),在您的情况下,这不是您想要的。