3

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

我有一个添加到购物车文件,它呈现一个带有按钮的表单。该按钮是另一个组件,所以我不想测试它。我必须测试表单的 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.
4

1 回答 1

6

考虑将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});
    });
});
于 2016-10-27T22:14:14.577 回答