【问题标题】:React Jest Testing onSubmitReact Jest 测试 onSubmit
【发布时间】:2016-10-27 18:18:59
【问题描述】:

我是新来的反应和开玩笑。我一直在到处寻找测试,但找不到任何有用的东西。这部分是因为我对它很陌生,我不知道从哪里开始。所以请多多包涵。

我有一个添加到购物车文件,它呈现一个带有按钮的表单。该按钮是另一个组件,所以我不想测试它。我必须测试表单的 onSubmit 函数。有什么想法吗?参考?

这是我目前的测试代码:

describe('AddToCart', () => {
  const React = require('react');
  const BaseRenderer = require('react/lib/ReactTestUtils');
  const Renderer = BaseRenderer.createRenderer();
  const ReactTestUtils = require('react-addons-test-utils');
  const AddToCart = require('../index.js').BaseAddToCart;

  it('Will Submit', () => {
    formInstance = ReactTestUtils.renderIntoDocument(<AddToCart product="" quantity=""/>);
    expect(ReactTestUtils.Simulate.onSubmit(formInstance)).toBeCalled();
  });
});

我收到此错误:

Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined.

【问题讨论】:

    标签: reactjs jestjs jasmine2.0


    【解决方案1】:

    考虑将JestEnzyme 结合使用。我认为这是反应单元测试的好堆栈。

    另外,我做了一个示例测试,测试 LogIn 组件中的 onSubmit 函数。

    import React from 'react';
    import {shallow} from 'enzyme';
    import LogIn from './LogIn';
    
    describe('<LogIn />', () => {
        const testValues = {
            username: 'FOO',
            password: 'BAZ',
            handleSubmit: jest.fn(),
        };
    
        it('Submit works', () => {
    
            const component = shallow(
                <LogIn {...testValues} />
            );
            component.find('#submitButton').simulate('click');
            expect(testValues.handleSubmit).toHaveBeenCalledTimes(1);
            expect(testValues.handleSubmit).toBeCalledWith({username: testValues.username, password: testValues.password});
        });
    });
    

    【讨论】:

    • 如果您要安装组件,这将无法正常工作。但是您可以使用:component.find('#submitButton').simulate('submit'); 来模拟提交事件。
    猜你喜欢
    • 2020-07-15
    • 2019-03-22
    • 1970-01-01
    • 1970-01-01
    • 2023-02-09
    • 2020-12-15
    • 2021-05-26
    • 2020-06-12
    • 2021-04-24
    相关资源
    最近更新 更多