CSS Unit Testing

前端 未结 9 1707
面向向阳花
面向向阳花 2020-12-24 05:35

A few quick searches discovered that I\'m obviously not the first person to have the thought \"Can I unit test my CSS?\".

I\'m wondering if anyone

9条回答
  •  既然无缘
    2020-12-24 06:13

    I think it would be possible in the browser (client-side) to "unit test" CSS. It would be more like an automated checker than an unit testing:

    1. Evaluate the final CSS attribute conditions we would like to preserve for a particular CSS class or ID (the result).
    2. We require a testing document HTML to render the static content and CSS. All elements should be included in the content in separate containers.
    3. After rendering, check with javascript the final or resulting final attributes of the selected targets and output non matching elements.

    Unit testing case:

    DOM selectors:

    .test1
    .test2
    #test3
    

    This should always be the final attributes:

    CSSAttribute1, CSSFinalValue1
    CSSAttribute2, CSSFinalValue2
    CSSAttribute3, CSSFinalValue3
    

    A function to set test rules in JS could be:

    addCSSUnitTest(".test1, .test2, #test3", "margin-left: 4px; font-size: 8px");
    

    Then we check if DOM elements have this final attributes.

    All done in javascript after rendering. But anyway this is not practical because you will have to construct many unit test cases that will increase your code significantly.

    Also you should always have a reset.css for cross-browser "compatibility".

    An alternative would be to designate CSS classes that you know should preserve their entire attributes. Create a list of DOM selectors. Use jQuery to get CSS class attributes (directly from the CSS class) and check if they are preserved in the target DOM elements. This last method could be almost fully automated, but will require a more complex javascript checker. This last one will not check CSS for ID selectors (e.g. "#test3"), only classes (e.g. ".test1")

提交回复
热议问题