尽管进行了 await userEvent.click() 操作,但 act() 警告仍然没有停止的原因和解决方案
首先
在使用React Testing Library进行测试时,如果要执行诸如点击操作等用户操作,可以使用testing-library/user-event库。例如,如果要进行点击操作,可以使用user.click()方法。在执行操作时,为了同步组件的状态更新,需要使用Promise的返回值并使用await进行等待。如果不这样做,将会出现”When testing, code that causes React state updates should be wrapped into act(…)”的警告提示。
然而,尽管我一直在努力解决这个问题,但警告经常无法消除。我曾长时间认为在异步函数中更新状态是不可行的,所以一直放弃尝试。最近我重新调查了一下,并找到了原因,所以本文将记录这一过程。
导致这个结果的因素
據說原因是安裝了多個版本的 @testing-library/dom。User event 將在 @testing-library/dom 中註冊包裝函數,但如果安裝了多個版本的 @testing-library/dom,這將導致它無法正常工作。實際上,執行 npm ls @testing-library/dom 可以確認已安裝了 8.20.0 和 9.2.0 兩個版本。
├─┬ @storybook/testing-library@0.1.0
│ ├── @testing-library/dom@8.20.0
│ └─┬ @testing-library/user-event@13.5.0
│ └── @testing-library/dom@8.20.0 deduped
├─┬ @testing-library/react@14.0.0
│ └── @testing-library/dom@9.2.0
├─┬ @testing-library/user-event@14.4.3
│ └── @testing-library/dom@8.20.0 deduped
├─┬ eslint-plugin-jest-dom@4.0.3
│ └── @testing-library/dom@8.20.0 deduped
└─┬ react-select-event@5.5.1
└── @testing-library/dom@8.20.0 deduped
更正
重新安装依赖于 @testing-library/dom 的库。
├─┬ @testing-library/react@14.0.0
│ └── @testing-library/dom@9.3.3
├─┬ @testing-library/user-event@14.5.1
│ └── @testing-library/dom@9.3.3 deduped
├─┬ eslint-plugin-jest-dom@5.1.0
│ └── @testing-library/dom@9.3.3 deduped
└─┬ react-select-event@5.5.1
└── @testing-library/dom@9.3.3 deduped
这样一来,所有的行为警告都已经解除了。