Imagine that you are making a chocolate cake and only after it is ready you realize that you forgot to add sugar to the dough, what now?! Think of your application like this cake batter, without testing it may even work well at first, but at some point while it is being tried something may not turn out as expected. And who is to guarantee that this trouble will not happen?!
Based on this example, tests are proof of the mass of your code, they ensure that everything is in the right place, even when you decide to add new layers or functionality coverage.
In general, automated tests are basically codes built to test other codes, ensuring that the application works with quality.
Since quality is the key word, it is important that within an engineering and product team everyone is aware of the importance and value that tests generate, so that they can be integrated into deliveries in a natural way.
I bring here some reasons to convince you to start implementing tests in your code right now:
Fail-safe code:Testing helps ensure that your code will work without bugs, even after you add new features or make changes.
Changes without fear:Application maintenance will be much safer as you will be able to refactor or update your code without worrying about breaking something as the tests warn you if something is wrong.
Faster fixes:With automated tests you will be able to fix problems more easily, saving you a lot more time
Less surprises when deploying:Can you imagine having just done the deployment and already receiving a call from users having an error in something that could have been predicted?! The tests come to help precisely with this prevention
Helping you and your QA colleague:Do you know when you finish that feature and pass it on to QA for testing and he gives you a report back with 357 things to fix? This problem will also be reduced since you will have predicted most of the errors he would probably encounter
There are many types of tests to be developed in the front-end, but today I will focus on three of them: User Interface Tests (UI), Functional Tests (End-to-End) and Validation Tests and to exemplify each one of them I will create tests for a simple login screen in an application in React.js using Testing Library.
User Interface (UI) Testing
User Interface (UI) Tests check whether components are being rendered as expected and, in addition to being based on rendering, check the existence of important elements, such as form fields, buttons and labels.
it('should render login form', () => { render(); expect(screen.getByLabelText(/email/i)).toBeInTheDocument(); expect(screen.getByLabelText(/senha/i)).toBeInTheDocument(); expect(screen.getByRole('button', { name: /login/i })).toBeInTheDocument(); });
What is being tested:This test ensures that the LoginForm component renders the essential interface elements: the email and password fields and the login button. screen.getByLabelText searches for elements by associated labels and screen.getByRole searches for buttons by their text and function.
Functional Tests (End-to-End)
Functional Tests or End-to-End (E2E) tests, verify the entire functioning of the application from the user's point of view, simulating real interactions with the interface, such as filling out forms and clicking buttons, and evaluating whether the application responds to interactions as expected.
it('should call onLogin with the username and password when submitted', async () => { const handleLogin = jest.fn(); render(); fireEvent.change(screen.getByLabelText(/email/i), { target: { value: 'larissa.tardivo@email.com.br' }, }); fireEvent.change(screen.getByLabelText(/senha/i), { target: { value: '123456' }, }); await fireEvent.click(screen.getByRole('button', { name: /login/i })); await waitFor(() => { expect(handleLogin).toHaveBeenCalledWith({ email: 'larissa.tardivo@email.com.br', password: '123456' }) }) await waitFor(() => { expect(handleLogin).toHaveBeenCalledTimes(1) }) });
What is being tested:Here, user interaction with the login form is simulated by filling in the email and password fields, and then clicking the login button. The test also checks that the onLogin function is called with the correct data and that it was called exactly once.
Validation Tests
Validation Tests ensure that the application validates invalid inputs and displays appropriate error messages. These tests are important to verify that the form handles incorrect data effectively and provides adequate feedback to the user.
test('should show error messages for invalid inputs', async () => { render(); fireEvent.change(screen.getByLabelText(/email/i), { target: { value: 'invalid-email' }, }); fireEvent.change(screen.getByLabelText(/senha/i), { target: { value: '123' }, }); await fireEvent.click(screen.getByRole('button', { name: /login/i })); expect(await screen.findByText(/Email inválido/i)).toBeInTheDocument(); expect(await screen.findByText(/A senha deve ter pelo menos 6 caracteres/i)).toBeInTheDocument(); });
O que está sendo testado:Aqui verificamos se o formulário está exibindo mensagens de erro adequadas quando os campos de e-mail e senha forem preenchidos com dados inválidos. Fazemos a simulação da entrada de valores incorretos verificando se as mensagens de erro esperadas são exibidas.
Em um mundo onde a experiência do usuário e a qualidade do software são prioridade, os testes no front-end desempenham um papel fundamental em garantir que nossas aplicações não apenas funcionem corretamente, mas também proporcionem uma experiência fluida e sem bugs.
Ao integrar esses testes no seu fluxo de desenvolvimento, você está não apenas prevenindo problemas antes que eles se tornem grandes dores de cabeça, mas também construindo uma base de código mais confiável e resistente. Cada tipo de teste tem uma camada diferente de verificação, e juntos, eles formam uma grande camada de segurança que ajuda a garantir a qualidade e a funcionalidade de sua aplicação.
Lembre-se, assim como em uma receita de bolo onde cada ingrediente tem seu papel crucial, cada tipo de teste tem sua função específica no processo de desenvolvimento e desenvolver uma combinação equilibrada de testes vai além de uma prática recomendada, é uma necessidade para qualquer equipe que se empenha em entregar um software de alta qualidade.
Então, da próxima vez que você estiver desenvolvendo um novo recurso ou corrigindo um bug, pense nos testes como seus aliados indispensáveis. Eles são a chave para uma aplicação mais robusta, confiável e, acima de tudo, mais satisfatória para seus usuários.
The above is the detailed content of Why should you start testing your application on the Front-End?. For more information, please follow other related articles on the PHP Chinese website!