Skip to content

Instantly share code, notes, and snippets.

@lmiller1990
Last active October 11, 2020 01:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lmiller1990/299871207f15220fb32490ae6a355767 to your computer and use it in GitHub Desktop.
Save lmiller1990/299871207f15220fb32490ae6a355767 to your computer and use it in GitHub Desktop.
If you have complex function that needs to be called when some dependency changes (eg with useEffect) you would just pull the function out and pass the dependency as an argument... same as you would do with watchEffect. In the react example you either need to pass setState as an argument to said complex business logic function (not ideal) or do the setState in the hook; eg
```js
const [result, useResult] = useState('foo')
useEffect(() => {
const result = complexBusinessLogic(someVariable)
setResult(result)
}, [someVariable])
```
Compare to Vue:
```
const someVariable = ref('foo')
watchEffect(() => {
const result = complexBusinessLogic(someVariable)
someVariable.value = result
})
```
Now you just unit test complex buiness logic in isolation, easy peasy... same pattern works for watchEffect, business logic unit test won't change since it's decoupled from the framework.
You still need some way to make sure the UI changes however it should when someVariable changes. This is the problem VTU, Cypress etc. solves.
If you are doing things in a very disciplined manner (eg: cypress for UI tests, plain JS for all business logic) you could swap from Vue to React and use the exact same test suite. This would be the ultimate test to see if you avoided testing implementation details. In this sense VTU and Enzyme are kind of anti-patterns - at least, the parts of the API that test implementation details are.
The answer is neither hooks/composition/options API is more or less testable - the real question is how well did you separate your concerns? Asking "which is more testable: Vue options/Vue composition/React hooks" is basically saying "which implementation detail is more testable"?
I wrote a little about that here: https://lachlan-miller.me/articles/writing-testable-forms (this is how I like to write my form validations; UI agnostic, since the UI library should not drive the business logic, but the other way around).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment