如何在反应测试库中模拟功能

时间:2020-03-29 15:45:14

标签: node.js reactjs jestjs react-testing-library

我是react-testing-library的新手,并且很长时间以来我一直在尝试测试一个功能。 例如,我想检查是否在单击按钮时调用了给定函数,并且该函数引发错误。因此,我们将不胜感激任何帮助,并在可能的情况下与我分享任何有用的资源。

signin.js

export default class SignIn extends Component {
    constructor(props) {
        super(props);
        this.state = {
        };
    }

    handleClose = (event, reason) => { };
    validate = () => { };
    change = (e) => { };
    onSubmit = (e) => { };

    render() {
        return (<div>...</div>);
    }
}

完整:https://github.com/blaise82/react-testing-library-try/blob/master/src/views/SignIn.js

这是我的考验

it('should submit form', async () => {
    const { getByLabelText, getByText, container, debug } = render(<SignIn />);
    const change = jest.fn();
    const onSubmit = jest.fn();
    const email = getByLabelText('email');
    const password = getByLabelText('password');
    const submit = getByLabelText('submit');

    userEvent.type(email, 'octopusbn@gmail.com');
    expect(email.value).toBe('octopusbn@gmail.com');
    expect(password.value).toBe('');
    expect(change).toHaveBeenCalled();

    console.log(password)
    await userEvent.click(submit);
    expect(onSubmit).toHaveBeenCalled();

});

完整:https://github.com/blaise82/react-testing-library-try/blob/master/src/test/signin.test.js

结果

>    Expected number of calls: >= 1
>     Received number of calls:    0

请告诉我我在做错什么。

GitHub上的完整代码:https://github.com/blaise82/react-testing-library-try

2 个答案:

答案 0 :(得分:1)

您可以通过模拟来自组件外部的函数来测试函数,例如-prop回调,外部库api等。

在开始之前,让我们先检查一下组件中的所有功能。 通过组件,我可以将它们列出如下:

  1. 事件处理程序(例如组件中的IF… THENIF rsdata4("ID") = rsdata("ID") THEN Response.Write ("XXX") END IF handleClose等元素)
  2. 组件内部的功能 ,不会与组件[onSubmit外部的状态/功能进行交互
  3. prop函数/库api被称为[change

让我们一个个地讨论它们-

  • 事件处理程序&
  • 组件内部的功能不与组件外部的状态/功能交互

==>附加到元素的事件处理程序将被调用。您无需测试它们是否被调用。相反,您应该测试的是它们被调用后的效果。还有validate

之类的功能

让我们以您要测试的axios.post函数为例。调用此函数后,将设置状态,并将状态反映到表单元素中。我们可以assert values of the form elements with a helper这样。

  • prop函数/库api被称为[validate

==>可以对这些函数进行模拟并测试它们被调用的调用/参数的数量。 https://jestjs.io/docs/en/mock-functions.html#mocking-modules

除了上面链接中给出的嘲笑笑话片段以外,您还可以-

change

您还可以使其返回所需的结果/错误并测试相应的组件行为。

希望这对您有所帮助。干杯!

答案 1 :(得分:-1)

我认为这是因为您实际上并未将模拟函数传递给组件。您只是实例化两个常量,这些常量恰好具有您要监视的函数的名称,但实际上并未在组件中的任何地方使用。

听起来您想监视组件的内部函数以查看它们已被调用。

以下是一个示例(未经测试),该示例基于可能对您有帮助的帖子(在下面链接)。

describe('spying on "onSubmit" method', () => {
  it('should call onSubmit when the button is clicked', () => {
    const wrapper = shallow(<SignIn />); 
    const instance = wrapper.instance();

    jest.spyOn(instance, 'onSubmit');

    wrapper.find('button').simulate('click');
    expect(instance.onSubmit).toHaveBeenCalled();
  });
});

帖子:https://bambielli.com/til/2018-03-04-directly-test-react-component-methods/#spying-on-incrementcounter