有没有办法测试私有方法?

时间:2019-06-24 20:40:47

标签: javascript reactjs jestjs private-methods react-testing-library

我有一个React组件'A'。它内部的一种方法“ foo”作为道具传递给组件“ B”。单击组件B会触发foo。

问题-如何测试此foo方法?

我可以通过将方法foo设为公共并分别对其进行测试来解决此问题。但是我不想公开。 我尝试但不起作用的另一种方法是触发组件B中的click事件,希望它可以调用foo方法。不知道是否可能,如果可能的话!

const A = () => {
    const foo = () => {console.log('Clicked!')}
    return (
      <B clickTrigger={foo} />
    )
}

3 个答案:

答案 0 :(得分:1)

听起来您想测试单击是否引起了组件的某些变化,而不仅仅是检查该方法是否被调用。

您可以呈现组件A,触发click事件,并根据引起组件输出变化的方式进行断言。使用react-testing-library的测试结果如下:

test('does a thing when clicked', () => {
  const { getByText } = render(<A />);
  // This assumes you have a button inside component B
  // that has `foo` as the onClick:
  fireEvent.click(getByText('Click me'));
  // Make assertions here based on how the click handler
  // causes the component's output to change, generally based
  // on some text changing
  expect(getByText('You clicked the button')).toBeInTheDocument();
})

答案 1 :(得分:0)

您应该模拟在foo函数中执行的代码。 通过此模拟,您将能够测试foo函数是否已成功调用。

答案 2 :(得分:0)

无法在闭包内部获取引用,因此您必须以某种方式将其导出到测试框架。有一种使用WeakMaps来存储私有状态的模式,如果测试框架可以访问WeakMap,则它可以在内部查看,而没有该引用的其他对象则不能。

let p = new WeakMap();
const A = () => {
    let foo = p.get(A);
    return (
        <B clickTrigger={foo} />
    );
};
p.set(A, () => {console.log('Clicked!')});

// Export A and p to testing framework but just A to clients