4 ms·
I haven't used React in a while so I'm happy to learn more. When I look at this example it does not look like the code I would be using inside my webapp. I hav
by xrd 2y ago
I haven't used React in a while so I'm happy to learn more.
When I look at this example it does not look like the code I would be using inside my webapp. I have a rule of thumb: my test code should look the same as the code when it is inside my app.
https://testing-library.com/docs/react-testing-library/example-intro#quickstart-annotated https://testing-library.com/docs/react-testing-library/examp...
My Svelte 5 runes test code uses the code in exactly the same way that I use it inside my .svelte templates. That's very different in my opinion.
- zdragnar 2y agotesting-library (and react-testing-library by extension) has a very dogmatic "black box" approach to testing FE code. In many ways it more closely resembles e2e testing than more traditional unit testing does. Personally, I think it's a PITA since it's pretty rare that copy (such as text labels) ever remains stable for very long, or are sufficiently unique on the page, so I do the "strongly discouraged" route of using data-testid attributes for everything (which also has the side effect of making people who write e2e tests happy, but I digress). With all of that said, I find myself rather appreciating the approach. I don't need tests to mirror the implementation, only the interface.
- wk_end 2y agoCan you link to/post an example of how Svelte is tested that's different? In the Full Example linked, the only code that it makes sense to talk about being in the app itself is the code to render the component, and that does look precisely the same. The rest is the testing logic - inspecting the state of the DOM post-render, interacting with components by simulating events, and so on. I don't see how this could correspond to anything in the app proper.
- crab_galaxy 2y agoYeah to be fair testing a fetch request is not the best example right off the bat. That's an outlier IMO. That said it's very very easy to write similar looking code using react testing library as long as you're good about separating business logic into a hook. Where it gets dicy & hard to test is when components have complex state/effects co-mingling with render logic. Business logic is very easily testable as a hook, something like: ``` it('toggles switch state', () => { const {current} = renderHook(() => useSwitchState); expect(current.checked).toBe(false); current.toggle(); expect(current.state).toBe(nextState); } ``` Render logic is a bit different because React Testing Library's philosophy is to test as a user would interact with the UI, so that looks more like: ``` it('switches state on button click', () => { render(<Switch onToggle={mockOnToggle} checked={false} />); getByRole('switch').click(); expect(mockOnToggle).toHaveBeenCalled(); }); ```