It's easiest to test code consisting of pure functions. Data to input, result to output. No surprises, no state, no interaction with the outside world.
import _ from 'lodash';
expect(_.last([1, 2, 3])).toBe(3);
Not all code can be called clean. No real program is without side effects. The results of the calculations need to be written down somewhere, sent, and saved.
Side effects dramatically complicate testing; they require deeper test-writing skills and a better understanding of how to organize this sort of code.
Here are just a few examples of how side effects can be used:
- Random numbers
- HTTP requests
- Sending emails
- Interacting with the database
- Interacting with global variables
- Reading and writing files
- Current time operation
Where does the difficulty come in? Imagine a function that sends an email to a user:
if (sendGreetingEmail(user)) {
// display a message on the site stating that the email has been sent
};
Here's a hypothetical test:
expect(sendGreetingEmail(user)).toBe(true);
There's definitely something wrong with this test. All we're checking here is that the function returns true
, but we don't know anything about whether this function sends an email, and if it does, then what kind of email? Is everything okay with this email?
But the reality is even more complicated. Sending real emails is by no means an option. First of all, it's not ethical in relation to people. Secondly, even if we send emails to fake accounts, we're still interacting with an external system. External systems take longer, such tests will take much longer to run than pure function tests. In addition, any interaction with an external environment is not deterministic; The network isn't reliable, the tests can crash for no apparent reason, and the mail service may block the IP address from which the mail is being sent for sending too many e-mails. And finally, it may not be safe.
And that's just sending emails. With other side effects, there'll be other difficulties. And solving them will require different approaches to organizing code and tests. Over the next few lessons, we'll go over the most common examples of side effects and how to deal with them properly.
Are there any more questions? Ask them in the Discussion section.
The Hexlet support team or other students will answer you.
For full access to the course you need a professional subscription.
A professional subscription will give you full access to all Hexlet courses, projects and lifetime access to the theory of lessons learned. You can cancel your subscription at any time.