Как проверить, когда рендеринг компонента компонента не удался - PullRequest
0 голосов
/ 19 сентября 2019

Например, если TestFailComponent пытается получить доступ к item.id, но элемент null:

describe("Should Fail Tests", () => {
  describe("render tests", () => {
    it("should fail to render since null has no id", () => {
      let shouldFail = mount(
        <MemoryRouter>
          <TestFailComponent
            item={null} />
        </MemoryRouter>
      );
      chai.expect(shouldFail.render).to.throw(new TypeError('null has no properties'))
    });

  });
});

Я также пытался:

chai.expect(shouldFail.exists()).to.be.false()
chai.expect(shouldFail.render).to.be.null()

related:

1 Ответ

1 голос
/ 19 сентября 2019

Вы можете создать компонент границы ошибки для его проверки.Полный файл, который работает:

import React from 'react';
import { mount } from 'enzyme';

// assume this component we want to test
const TestFailComponent = ({ items }) => {
    if (items == null) {
        throw new TypeError('null has no properties');
    }
    return 'hello world';
};

// We create a component-helper
class ErrorCatching extends React.Component {
    state = { hasError: false };
    // we need to change state, so that render cycle could be completed
    static getDerivedStateFromError() {        
        return { hasError: true };
    }
    // catch error and test it
    componentDidCatch(error, errInfo) {        
        // we even can check componentStack field into errInfo arg
        this.props.processError(error, errInfo);
    }
    render() {
        // after the first error we render nothing
        if (this.state.hasError) {
            return null;
        }
        return this.props.children;
    }
}

describe('Should Fail Tests', () => {
    describe('render tests', () => {
        it('should fail to render since null has no id', () => {
            // our expected error
            const expectedError = new TypeError('null has no properties');

            mount(
                <ErrorCatching processError={(error) => expect(error).toEqual(expectedError)}>
                    <TestFailComponent item={null} />
                </ErrorCatching>
            );
        });
    });
});

Вы также можете проверить результат рендеринга, который будет нулевым.

Подробнее об обработке ошибок: https://reactjs.org/docs/react-component.html#error-boundaries и https://reactjs.org/blog/2017/07/26/error-handling-in-react-16.html#targetText=Error%20boundaries%20are%20React%20components,the%20whole%20tree%20below%20them.

...