如何测试是否已从切换状态渲染了React组件?

时间:2019-06-10 09:38:06

标签: javascript reactjs mocha enzyme chai

我有一个名为ModalContainer的文件,该文件使用基于道具的switch语句渲染子组件。

@receiver(sender=BackOperator, signal=pre_save)
def change_log(**kwargs):
    instance = kwargs['instance']
    try:
        original_object = BackOperator.objects.using('operator').get(pk=instance.pk)
    except:
        return
    if original_object:
        field_names = [field.name for field in original_object._meta.fields]

        for field in field_names:
            try:
                ori_field = getattr(original_object, field)
                new_field = getattr(instance, field)
                message = (field + ": " + str(ori_field) + " changed to: " + str(new_field))
                if ori_field != new_field:
                    BackNote.objects.using('operator').\
                        create(operator=instance.pk, note=message)
            except:
                return

我正在安装ModalComponent并传递道具,但是当我尝试控制台记录输出时,我得到sudo -i myfunc,我不能将其用于断言测试。

这是我的考试

render() {
    let visibleElement = null;
    switch (this.props.modal) {
      case constants.SEARCH_AND_HIGHLIGHT_MODAL:
        visibleElement = <SearchAndHighlightModal/>;
        break;
      case constants.SAVE_SNIPPET_MODAL:
        visibleElement = <SaveSnippetModal/>;
        break;
      case constants.SNIPPET_SAVED_MODAL:
        visibleElement = <SnippetSavedModal/>;
        break;
      case constants.SAVE_SEARCH_MODAL:
        visibleElement = <SaveSearchModal/>;
        break;
      default visibleElement = null;

我已经在单独的测试用例中测试了每个子组件,只需要测试文件的这一部分。 谢谢

1 个答案:

答案 0 :(得分:1)

要测试子组件是否正确呈现,可以按照以下给出的模式进行操作:

import {shallow} from "enzyme/build";
import ThemeProvider from "./mock-themeprovider";
import React from "react";
import ParentComponent from "./ParentComponent";
import ChildComponent from "./ChildComponent";

it("Does component renders child component correctly based on type?", () => {
    const component = shallow(<ThemeProvider value="primary">
        <ParentComponent
            type={1} //for type 1 assuming it renders ChildComponent
        />
    </ThemeProvider>);
    console.log(component.debug());
    const content = component.find(ParentComponent).dive().dive().find(ChildComponent);
    expect(content.exists()).toEqual(true);
});

根据ParentComponent的实现,您可能必须执行多次.dive()甚至一次都不需要。

以浅层方法编写测试用例.debug()时快速查看树可以节省大量时间!