13

测试异步调用componentDidMount是否为 React 组件设置状态的最佳方法是什么?对于上下文,我用于测试的库是MochaChaiEnzymeSinon.

这是一个示例代码:

/* 
 * assume a record looks like this:
 * { id: number, name: string, utility: number }
 */

// asyncComponent.js
class AsyncComponent extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            records: []
        };
    }

    componentDidMount() {
        // assume that I'm using a library like `superagent` to make ajax calls that returns Promises

        request.get('/some/url/that/returns/my/data').then((data) => {
            this.setState({
                records: data.records
            });
        });
    }

    render() {
        return (
            <div className="async_component">
                { this._renderList() }
            </div>
        );
    }

    _renderList() {
        return this.state.records.map((record) => {
            return (
                <div className="record">
                    <p>{ record.name }</p>
                    <p>{ record.utility }</p>
                </div>
            );
        });
    }
}


// asyncComponentTests.js
describe("Async Component Tests", () => {
    it("should render correctly after setState in componentDidMount executes", () => {
        // I'm thinking of using a library like `nock` to mock the http request

       nock("http://some.url.com")
           .get("/some/url/that/returns/my/data")
           .reply(200, {
               data: [
                   { id: 1, name: "willson", utility: 88 },
                   { id: 2, name: "jeffrey", utility: 102 }
               ]
           });

       const wrapper = mount(<AsyncComponent />);

       // NOW WHAT? This is where I'm stuck.
    });
});
4

3 回答 3

2

所以,你真正想要测试的是,基于一些模拟数据,它“应该正确呈现......”

正如一些人指出的那样,实现这一点的一个好方法是将数据获取逻辑放入一个单独的容器中,并拥有一个只知道如何呈现的“哑”表示组件props

这是如何做到这一点的:(我不得不用 Tslint 为 Typescript 稍微修改一下,但你会明白的)

export interface Props {
    // tslint:disable-next-line:no-any
    records: Array<any>;
}

// "dumb" Component that converts props into presentation 
class MyComponent extends React.Component<Props> {
    // tslint:disable-next-line:no-any
    constructor(props: Props) {
        super(props);
    }

    render() {
        return (
            <div className="async_component">
                {this._renderList()}
            </div>
        );
    }

    _renderList() {
        // tslint:disable-next-line:no-any
        return this.props.records.map((record: any) => {
            return (
                <div className="record" key={record.name}>
                    <p>{record.name}</p>
                    <p>{record.utility}</p>
                </div>
            );
        });
    }
}

// Container class with the async data loading
class MyAsyncContainer extends React.Component<{}, Props> {

    constructor(props: Props) {
        super(props);

        this.state = {
            records: []
        };
    }

    componentDidMount() {

        fetch('/some/url/that/returns/my/data')
        .then((response) => response.json())
        .then((data) => {
            this.setState({
                records: data.records
            });
        });
    }

    // render the "dumb" component and set its props
    render() {
        return (<MyComponent records={this.state.records}/>);
    }
}

现在,您可以MyComponent通过将模拟数据作为道具来测试渲染。

于 2018-03-08T08:41:39.177 回答
-1

IMO,这实际上是一个常见问题,由于承诺而显得更加复杂componentDidMount:您正在尝试测试仅在另一个函数范围内定义的函数。即您应该将您的功能分开并单独测试它们。

零件

class AsyncComponent extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            records: []
        };
    }

    componentDidMount() {
        request.get('/some/url/that/returns/my/data')
            .then(this._populateState);
    }

    render() {
        return (
            <div className="async_component">
                { this._renderList() }
            </div>
        );
    }

    _populateState(data) {
        this.setState({
            records: data.records
        });
    }

    _renderList() {
        return this.state.records.map((record) => {
            return (
                <div className="record">
                    <p>{ record.name }</p>
                    <p>{ record.utility }</p>
                </div>
            );
        });
    }
}

单元测试

// asyncComponentTests.js
describe("Async Component Tests", () => {
    describe("componentDidMount()", () => {
        it("should GET the user data on componentDidMount", () => {
            const data = {
                records: [
                    { id: 1, name: "willson", utility: 88 },
                    { id: 2, name: "jeffrey", utility: 102 }
                ]
            };
            const requestStub = sinon.stub(request, 'get').resolves(data);
            sinon.spy(AsyncComponent.prototype, "_populateState");
            mount(<AsyncComponent />);

            assert(requestStub.calledOnce);
            assert(AsyncComponent.prototype._populateState.calledWith(data));
        });
    });

    describe("_populateState()", () => {
        it("should populate the state with user data returned from the GET", () => {
            const data = [
                { id: 1, name: "willson", utility: 88 },
                { id: 2, name: "jeffrey", utility: 102 }
            ];

            const wrapper = shallow(<AsyncComponent />);
            wrapper._populateState(data);

            expect(wrapper.state).to.deep.equal(data);
        });
    });
});

注意:我仅根据文档编写了单元测试,因此使用shallowmountassertexpect可能不是最佳实践。

于 2018-01-26T14:47:22.833 回答
-1

忽略重新考虑结构的理智建议,解决此问题的一种方法可能是:

  • 模拟请求(fx with sinon),使其返回一些记录的承诺
  • 使用酶的mount功能
  • 断言该州还没有您的记录
  • 让你的休息功能使用done回调
  • 稍等(fx with setImmediate),这将确保您的承诺得到解决
  • 再次断言已安装的组件,这次检查状态是否已设置
  • 调用 done 回调以通知测试已完成

所以,简而言之:

// asyncComponentTests.js
describe("Async Component Tests", () => {
    it("should render correctly after setState in componentDidMount executes", (done) => {
        nock("http://some.url.com")
           .get("/some/url/that/returns/my/data")
           .reply(200, {
               data: [
                   { id: 1, name: "willson", utility: 88 },
                   { id: 2, name: "jeffrey", utility: 102 }
               ]
           });

        const wrapper = mount(<AsyncComponent />);

        // make sure state isn't there yet
        expect(wrapper.state).to.deep.equal({});

        // wait one tick for the promise to resolve
        setImmediate(() => {
            expect(wrapper.state).do.deep.equal({ .. the expected state });
            done();
        });
    });
});

笔记:

我对诺克一无所知,所以在这里我假设您的代码是正确的

于 2017-08-28T07:42:16.153 回答