[Unit testing] data-test attr FTW

Most of time, we get used to use class name as a selector in the test.

But one problem for this is classname is used for styling, when we also use it for testing, we are not sure whether we can remove the classname whether it will break the tests.

Another thing is in React, we use CSS-in-JS approache, then class based test approach is no go.

The way we can use is by using "data-test":

<fieldset className="form-group">
        <input
          className="form-control form-control-lg"
          type="email"
          placeholder="Email"
          data-test="email"
        />
      </fieldset>
const emailField = rootNode.querySelector('[data-test="email"]')

 

Even better, we can make a help function:

const sel = id => `[data-test="${id}"]`
const emailField = rootNode.querySelector(sel('email'))

 

Blog

posted @ 2017-10-30 18:19  Zhentiw  阅读(247)  评论(0编辑  收藏  举报