React应用程序中className Test实用程序的替代方案

Alternative of className Test utility in React application

本文关键字:方案 实用程序 Test 应用程序 className React      更新时间:2023-09-26

在移动外部CSS文件并重构为JS对象以支持react-inline 之后,我在React应用程序中编写测试用例时遇到了一些困难

早些时候,对于我的测试用例,我一直在使用className来检查预期的class是否存在于我的组件中。由于我不再使用类,我在重构测试时遇到了一些困难。例如,如果在我的化身组件中传递rounded样式的道具,我一直在检查类avtarimg-rounded是否存在。

it("should render image with rounded style if style is 'rounded'", done => {
        let user = { displayName: "Foo", avatar: { url: "http://some.url"} };
        renderer.render(
            <UserAvatar user={user} style="rounded" />
        );
        let result = renderer.getRenderOutput();
        expect(result.type).toEqual("img");
        expect(result.props.className).toEqual("avatar img-rounded");
        expect(result.props.src).toEqual("http://some.url");
        done();
    });

现在,我将基于传递的style道具将关联的样式直接添加到react组件中。

_getAvatarStyles() {
        let avatarStyle = {
            borderRadius: "50%"
        };
        if (this.props.style === "circle" || this.props.style === "text-only" || this.props.style === "initials") {
            avatarStyle = {
                borderRadius: "50%"
            };
        } else if (this.props.style === "rounded") {
            avatarStyle = {
                borderRadius: "10%"
            };
        }
        return avatarStyle;
    },

在重构之前,我将className直接添加到组件中,如下所示:

_getAvatarClasses() {
        return classNames({
            "avatar": true,
            "img-rounded": this.props.style === "rounded",
            "img-circle": this.props.style === "circle"
        });
    },

有没有什么方法可以直接检查img标签中的style属性。例如,如果组件具有borderRadius: "50%",则为圆形化身返回true,如果组件有borderRadius: "10%" ,则为圆角化身返回true

您是否考虑过使用Sinon.js这样的测试库并监视函数以测试其返回值?它基本上会完成同样的事情,看起来像这样:

it("should render image with rounded style if style is 'rounded'", done => {
        let user = { displayName: "Foo", avatar: { url: "http://some.url"} };
        renderer.render(
            <UserAvatar user={user} style="rounded" />
        );
        let result = renderer.getRenderOutput();
        let spy = sinon.spy(result, "_getAvatarStyles");
        result.forceUpdate(); //If '_getAvatarStyles()' is called on render, this allows it to be called again
        let expected = {
            borderRadius: "10%"
        };
        expect(spy.returned(expected)).toBe(true);
        done();
});