# 測試筆記
https://www.w3.org/TR/wai-aria/#role_definitions
https://testing-library.com/docs/dom-testing-library/api-accessibility/#logroles
建議使用 ByRole 因為 screen reader 可讀到。logroles method 協助你找到你的 role。
v14 userEvent api always return promise 所以使用它記得要 await before assertion
testing library
1. cheet sheet: https://testing-library.com/docs/react-testing-library/cheatsheet/
2. about queries: https://testing-library.com/docs/queries/about/#priority
for element starts out not on pages -> queryByText
# msw
npm install msw
* create handlers
* create test server
* make sure test servers listen to all test and reset after each test
> anytime you waiting for sth async on the page, you must use await findby - for async dom update on the element
due to race conditions, depend on your computer, you may not see the error.
如果斷言的速度比 network 們回來的速度快,就可能會看到這個錯誤。解決方法:waitFor
# others
array and objects need to use toEqual
將找元素與斷言分開,會提升可讀性
測試過將中應考慮盲盒測試,不考慮實作過程。
{exact: false} is not an option for *byRole
# context
make context with create context, and export custom hook and provider
1. make contextProvider with internal useState. Providers value state setter and getter.
2. make custom hooks with useContext
createContext & useContext 解說
https://juejin.cn/post/6989054367064129573
`render(<Options optionType="scoops" />, { wrapper: OrderDetailsProvider });` 不會想每個地方都加上去,會希望集中管理
# 常見非同步 msg
```text
Warning: Can't perform a React state update on an unmounted component.
Warning: An update to Options inside a test was not wrapped in act(...)
Cannot log after tests are done. Did you forget to wait for something async in your test?
Attempted to log "Warning: An update to Options inside a test was not wrapped in act(...).
```
component is changing after the test is over. test function quits before state updates are complete.
原因:race condition
1. test renders component 測試載入虛擬 dom
2. component trigger network calls
3. test function exits and testing library do some cleanup and umount component
4. network calls returns
component unmount before the network returns -> race trigger
解決方法:把流程改成這樣
1. test renders component 測試載入虛擬 dom
2. component trigger network calls
3. unmount component
4. network calls is canceled
5. test function exits
# debug method
* screen.debug
* logRoles (testing-library/dom 提供的 api)- to see what roles there are in your DOM
# pass a mock as prop
jest.fn() - don't do anything. It's just a placeholder to avoid error.
# Before testing, you should know ...
1. what to render - what's the smallest component that encompasses test
2. do we need to pass any prop?
3. do we need to wrap in provider? does the provider get used?
4. where should the test goes? which file? new file?
5. what to test?
6. how to test? which queries?
7. do we need to await? Is there any asnyc going?