前端小栈react 单元测试前端魔法世界

如何处理React snapshot 中 lifecycles

2019-02-26  本文已影响39人  _TheSpecialOne

我们在React App中会对Component进行snapshot测试比较,主要原理是将Component Render成一定格式的数据留存为snapshot,每次测试的时候动再次动态Render和snapshot进行比较,以防手滑或者其他原因改了Component而测试没有覆盖而产生的生产问题。

可爱的Snapshot的确帮助我们避免了很多”手滑“问题,但是坑人的时候也一点不含糊。。。

在本地执行 npm run test 完美通过之后, 却在生产的Drone build 上面fail了所有的snapshot检查,

  Symbol(enzyme.__options__): Object {
         "adapter": ReactSixteenAdapter {
           "options": Object {
             "enableComponentDidUpdateOnSetState": true,
    +        "legacyContextMode": "parent",
    +        "lifecycles": Object {
    +          "componentDidUpdate": Object {
    +            "onSetState": true,
    +          },
    +          "getChildContext": Object {
    +            "calledByRenderer": false,
    +          },
    +          "getDerivedStateFromProps": true,
    +          "getSnapshotBeforeUpdate": true,
    +          "setState": Object {
    +            "skipsComponentDidUpdateOnNullish": true,
    +          },
    +        },
           },
         },
       },

起初怀疑drone build 上的jest版本不一致导致如此差异,尝试了换成和本地一样版本后,依然没有任何改变,猜测问题在于新产生的lifecycles节点上。
Github 上找到一个这样 issue, 和我的问题一致,其中有一个回复帮忙解决了lifecycles 问题。

I solve this issue by removing the node_modules, and run yarn install, then generate new yarn.lock and test snapshot.
Before I use npm install, something wrong here ...

尝试删除React App中的 node_modulespackage.lock.json 之后,重新运行 CI=true npm test -- -u, 在本地新生产的snapshot都拥有了 lifecycles 节点,问题算是处理好了。

但是出现了新的问题,
在删除node_modulespackage.lock.json 之前我试图运行过好几次
CI=true npm test -- -usnapshot并未发生改变。

为什么会产生 lifecycles 节点?值得再次思考和调查的问题。

上一篇下一篇

猜你喜欢

热点阅读