Keep tests short
If they run against a product with a UI that is evolving over time, scripts will need to be regularly updated. This brings up two important points:- Most scripts are not write-and-forget, so each script we write is one more script we will have to maintain.
- Like all cases where code and refactoring are involved, how we write scripts can have a significant influence on how long this maintenance effort takes.
- Simplicity: keep in mind the goal of the script, and keep away from overly complex solutions whenever possible.
- Conciseness: simply put, do not be overly verbose and keep scripts as short as they can be.
- Readability: follow general best practices around writing code that is easy to read.
Do not underestimate the compounding effect of having messy scripts across a large test base.
Keep tests focused
Automated tests are effective if they:- Correctly verify the status of the target functionality.
- Return within a reasonable amount of time.
- Produce a result that can be easily interpreted by humans.
Always check the assertions in your test: if they are spanning more than one feature, you would likely be better off splitting your test into multiple different ones.
Keep tests independent
In an effort to remove duplication, tests are often made dependent on the previous execution of one or more other tests. An example could be the following sequence of tests:- Lower test result readability: we might need to backtrack and look into previous tests when trying to understand what a subsequent one is doing
- Harder maintenance: changes might need to be applied across different scripts
- Lack of flexibility and parallelisation: tests need to run sequentially in a specific order to work
- Tests can be run in any order, even at the same time.
- In the interest of code quality, we would be factoring out setup phases in order to easily reuse them across tests. Jest’s
beforeEach
andbeforeAll
hooks are examples of useful helper functions that can help us achieve that.
If the system you are testing allows it, provision/deprovision your users through APIs in your setup and teardown phases to save time and increase test reliability.
Takeaways
- Tests should be reliable and informative in order to be useful.
- Keep tests short and focused on testing one feature.
- Keep tests independent to maximise their parallelisation potential and reduce total runtime.
Further reading
- Gergely Orosz on writing readable code.