¿Qué es la prueba de humo? Construya pruebas de verificación explicadas con ejemplos

Esto puede sonar familiar: alguien empujó el código a producción y ahora una característica crítica está rota. ¿Cómo puede evitar que esto suceda en el futuro?

vía GIPHY

En este tutorial, aprenderá sobre las pruebas de humo y cómo ayuda a detectar insectos. Luego, probará una aplicación web en un horario y enviará alertas cuando las pruebas fallan. ¡Empecemos!

  1. ¿Qué es la prueba de humo?
  2. ¿Por qué debería preocuparte?
  3. Configura tu proyecto
  4. Crea una prueba de humo
  5. Revisar el código de prueba
  6. Ejecute su prueba localmente
  7. Ejecutar pruebas en acciones de GitHub
  8. Configurar alertas con Slack
  9. Conclusión

1. ¿Qué es la prueba de humo?

El término "prueba de humo" se originó en la reparación de hardware. Se encendió un dispositivo y fallaría la prueba de humo si se incendiaba. ? Las pruebas de humo a veces se denominan "pruebas de verificación de construcción".

Cuando se aplican a aplicaciones web, las pruebas de humo verifican que la funcionalidad más importante esté funcionando. Por ejemplo, las pruebas de humo en Netflix pueden incluir iniciar sesión y reproducir un video.

Por diseño, las pruebas de humo no cubren todos los casos de permutación y borde. En su lugar, comprueban que su aplicación no esté tan rota que las pruebas adicionales sean una pérdida de tiempo.

2. ¿Por qué debería importarle?

Las pruebas de humo proporcionan mucho valor en relación con el esfuerzo necesario para crearlas. Según Microsoft, las pruebas de humo son "el método más rentable para identificar y corregir defectos en el software" después de la revisión del código.

vía GIPHY

Solo unas pocas pruebas de funciones críticas como el inicio de sesión pueden mejorar significativamente la calidad. Probar lo que los usuarios hacen con más frecuencia ayuda a garantizar que los principales casos de uso de su aplicación sean compatibles.

Las pruebas de humo también le dan a su equipo la confianza para enviar un nuevo código. Los cambios en su código base a menudo tienen consecuencias no deseadas y desconocidas. Las pruebas de humo brindan tranquilidad adicional de que su aplicación no se romperá cuando lance esa nueva característica increíble.

Si ejecuta pruebas de humo en producción, también puede detectar errores que las pruebas anteriores no detectaron. Incluso las pequeñas diferencias entre entornos como la puesta en escena y la producción pueden causar problemas. Las pruebas de humo pueden identificar estos problemas antes que el cliente.

En resumen, las pruebas de humo le brindan otra capa de protección contra una mala experiencia de usuario. Una aplicación que se ejecute sin problemas ayuda a su equipo, su empresa y sus clientes a tener más éxito.

3. Configura tu proyecto

Ahora que hemos aprendido qué es la prueba de humo, ¡construyamos una tubería de prueba de humo!

vía GIPHY

Este tutorial asume que comprende la línea de comandos, tiene Node.js npminstalado y conoce los conceptos básicos de JavaScript y Git.

Puede configurar sus pruebas dentro de un proyecto existente o crear uno nuevo. Para crear un nuevo proyecto, ejecute lo siguiente en la línea de comando.

mkdir smoke_tests cd smoke_tests

Si aún no lo ha hecho, inicialice su proyecto para que pueda instalar los paquetes de Node.js.

npm init -y

Ahora instalemos las herramientas que necesitamos para crear nuestras pruebas de humo. Este tutorial creará pruebas de dramaturgo y broma en una aplicación web. Playwright es una biblioteca creada por Microsoft para automatizar los navegadores Chromium, Firefox y WebKit. Jest es un marco para crear y ejecutar pruebas de JavaScript.

Para crear y ejecutar nuestras pruebas rápidamente, usaremos la biblioteca QA Wolf de código abierto que ayudo a mantener. QA Wolf convierte las acciones de su navegador en código de prueba de dramaturgo / broma. También ejecuta sus pruebas en un proveedor de CI como GitHub Actions.

Si prefiere utilizar otro marco de prueba, aún puede seguir este tutorial para ejecutar sus pruebas en CI y configurar alertas.

Para configurar su proyecto para pruebas de humo, ejecute lo siguiente en el directorio de su proyecto.

npm init qawolf

Se le pedirá que especifique el directorio donde se guardarán sus pruebas. Presione Entrar para usar el directorio predeterminado .qawolfo escriba un nombre diferente.

? rootDir: Directory to create tests in (.qawolf)

Luego verá una nota en la línea de comando que indica si sus pruebas usarán TypeScript. Nuestro proyecto de ejemplo no tiene un archivo "tsconfig.json", por lo que nuestras pruebas no usarán TypeScript.

TypeScript ✖️ tsconfig.json not found

El último paso es elegir su proveedor de CI. Este tutorial usará acciones de GitHub, pero puede elegir otro proveedor si lo desea. Seleccione su proveedor de CI en la línea de comando y presione Entrar.

? Choose CI Provider (Use arrow keys) Azure DevOps Bitbucket Pipelines CircleCI ❯ GitHub Actions GitLab CI/CD Jenkins Skip CI setup 

A continuación, se instalarán los paquetes necesarios para las pruebas de humo (Playwright, Jest y QA Wolf).

También se crearán dos archivos en su proyecto. El primero es un archivo de flujo de trabajo para ejecutar sus pruebas en CI. Como seleccionamos Acciones de GitHub, este archivo se guarda en ".github / workflows / qawolf.yml". Discutiremos este archivo más adelante.

También hay un archivo de configuración creado en "qawolf.config.js". No necesitaremos editar este archivo, pero puede obtener más información aquí.

Una vez que las dependencias terminen de instalarse, compruebe que la instalación se haya realizado correctamente.

npx qawolf howl

4. Cree una prueba de humo

Ahora que nuestro proyecto está configurado, creemos nuestra primera prueba de humo. En este tutorial crearemos una prueba de humo en TodoMVC, una aplicación sencilla de hacer. Específicamente, probaremos que podemos

  1. crear un elemento de tarea,
  2. completarlo, y
  3. borrar todos los completados.

To create our test, we'll use the npx qawolf create command. This command takes the URL of your application and an optional test name. Running this command will open a Chromium browser where your actions will be converted to Playwright/Jest code.

In the command line, run the following. You can optionally replace //todomvc.com/examples/react with a different URL, and myFirstTest with a different name.

npx qawolf create //todomvc.com/examples/react myFirstTest

Open your code editor and find your test file (".qawolf/myFirstTest.test.js" in our example). This is where your test code will be created as you use the browser.

Once the Chromium browser has opened to TodoMVC, take the following actions.

  1. Click on the todo input to focus it
  2. Type "create test!"
  3. Press Enter
  4. Click to complete the todo
  5. Click "Clear completed" to clear completed todos
  6. In the command line, highlight ? Save and Exit and press Enter to save your test

The video below provides an example.

5. Review test code

Now let's take a look at our test code. In your code editor, open your test file (".qawolf/myFirstTest.test.js" in our example).

At the beginning of our test, we import qawolf. We also import element selectors from ".qawolf/selectors/myFirstTest.json", which we will discuss in a bit.

const qawolf = require("qawolf"); const selectors = require("./selectors/myFirstTest.json");

The test then launches a Playwright browser, which in our case is a Chromium browser. It creates a new Playwright browserContext, which is an incognito browser session. QA Wolf is given access to the context so it can detect your actions. Finally, a new Playwright page is created, opening a new tab in the browser.

let browser; let page; beforeAll(async () => { browser = await qawolf.launch(); const context = await browser.newContext(); await qawolf.register(context); page = await context.newPage(); });

The test itself is contained in a Jest test block with the name you specified. The test first navigates to the TodoMVC URL. It then goes through the actions you took: create a todo item, complete it, and clear completed todos. Each action uses one of Playwright's page methods, like click and type.

test('myFirstTest', async () => { await page.goto("//todomvc.com/examples/react"); await page.click(selectors["0_what_needs_to_b_input"]); await page.type(selectors["1_what_needs_to_b_input"], "create test!"); await page.press(selectors["2_what_needs_to_b_input"], "Enter"); await page.click(selectors["3_input"]); await page.click(selectors["4_button"]); });

The first argument passed to each page method is an HTML selector. This selector tells Playwright what element to interact with, like the todo input or "Clear completed" button. These selectors are imported from the  ".qawolf/selectors/myFirstTest.json" file, which looks like the following.

{ "0_what_needs_to_b_input": "html= ", // ... } 

Every attribute of the element you interacted with, as well as those of its two ancestors, is stored in this file. When you run your test, it will do its best to find a good enough match to the specified HTML. By not relying on a single attribute, your tests are more robust to changes in your front end code.

Playwright page methods also support other types of selectors, such as CSS selectors or text selectors. For example, you can replace selectors["4_button"] in the last step with the CSS selector '.clear-completed'.

test('myFirstTest', async () => { // ... // change this await page.click(selectors["4_button"]); // to this (CSS selector) await page.click('.clear-completed'); });

You can optionally configure QA Wolf to use test attributes like data-qa in the generated code whenever possible. See this guide to learn more.

After the test finishes running, QA Wolf stops recording any videos of the browser if applicable. The browser is also closed.

afterAll(async () => { await qawolf.stopVideos(); await browser.close(); });

Putting it all together, the complete test code looks like this.

const qawolf = require("qawolf"); const selectors = require("./selectors/myFirstTest.json"); let browser; let page; beforeAll(async () => { browser = await qawolf.launch(); const context = await browser.newContext(); await qawolf.register(context); page = await context.newPage(); }); afterAll(async () => { await qawolf.stopVideos(); await browser.close(); }); test("myFirstTest", async () => { await page.goto("//todomvc.com/examples/react"); await page.click(selectors["0_what_needs_to_b_input"]); await page.type(selectors["1_what_needs_to_b_input"], "create test!"); await page.press(selectors["2_what_needs_to_b_input"], "Enter"); await page.click(selectors["3_input"]); await page.click(selectors["4_button"]); });

If the test cannot complete the workflow, it will fail. You are welcome to edit your test code, such as by adding assertions. We won't go into that in this tutorial, but here is a guide if you'd like to learn more.

Now that we understand our test code, let's run our test!

6. Run your test locally

Let's run our test locally to make sure it works. In the command line, run the following to run your test(s) with Jest.

npx qawolf test

You should see a Chromium browser open and run the test. Your test will run as fast as possible, so don't be surprised if it runs quickly.

The video below provides an example.

7. Run tests in GitHub Actions

In this tutorial we'll run our tests on a schedule, such as every hour. Running tests on a schedule ensures that your application is working on an ongoing basis. It can also expose periodic issues, or "flakes", that only appear sometimes.

In this tutorial we use GitHub Actions to run our tests. GitHub Actions is a tool to automate software workflows, such as deploying a web service or testing an application.

Review workflow file

When we set up our project, a YAML file called ".github/workflows/qawolf.yml" was created. We'll first briefly go through the different parts of this file. We will then update it so our tests run on a schedule.

The first line of the workflow file names our workflow. This is the name that will show up in GitHub Actions, and you can change it if you like.

name: qawolf

The on key then specifies what event should trigger our tests to run. By default, your tests will run whenever someone pushes to any branch. We will soon edit this to also run our tests on a schedule.

on: push: # test every branch # edit below if you only want certain branches tested branches: "*" # schedule: # # test on schedule using cron syntax # - cron: "0 * * * *" # every hour

The rest of the file defines what GitHub Actions should do when it runs. GitHub Actions will run whatever jobs are listed under the jobs key. In our case we have just one job that runs our tests.

Specifically, our test job installs dependencies, checks out our code, and runs our test command npx qawolf test. After the test(s) run, debug artifacts like console logs and videos are saved.

jobs: test: runs-on: ubuntu-18.04 steps: - name: Install dependencies run: | sudo apt update # chromium dependencies sudo apt-get install libgbm1 # webkit dependencies sudo apt-get install libwoff1 libopus0 libwebp6 libwebpdemux2 libenchant1c2a libgudev-1.0-0 libsecret-1-0 libhyphen0 libgdk-pixbuf2.0-0 libegl1 libgles2 libevent-2.1-6 libnotify4 libvpx5 libxslt1.1 - uses: actions/[email protected] - uses: actions/[email protected] - uses: actions/[email protected] with: path: ~/.npm key: ${{ runner.os }}-node-${{ hashFiles('**/package-lock.json') }} restore-keys: | ${{ runner.os }}-node- - run: npm install # - name: Start local server # run: npm run start & npx wait-on //localhost:3000 - run: npx qawolf test --headless env: # configure tests with environment variables QAW_ARTIFACT_PATH: ${{ github.workspace }}/artifacts # you can also use GitHub secrets for environment variables # //help.github.com/en/actions/automating-your-workflow-with-github-actions/creating-and-using-encrypted-secrets # LOGIN_PASSWORD: ${{ secrets.PASSWORD }} - name: Upload Artifacts if: always() uses: actions/[email protected] with: name: qawolf path: ${{ github.workspace }}/artifacts

Run tests in GitHub Actions

Now that we understand our workflow file a bit better, let's run it in GitHub Actions. If you have not already, create a Git repository for your project. Make sure to ignore node_modules/ in your ".gitignore" file.

git init git add . git commit -m "Initial commit"

Make sure you have created a repository for your project on GitHub. Then push your code to GitHub.

git remote add origin YOUR_REPOSITORY_URL git push -u origin master

See this GitHub repository for an example.

Now go to your GitHub repository and click on the "Actions" tab, which is next to the "Pull Requests" tab.

You will see that your tests are running. This is because our workflow file told GitHub to run our tests whenever anyone pushed to any branch. Click on the workflow run to view details. Note that the name will vary depending on your commit message.

After your test runs, you should see a green check mark indicating that the workflow was successful. You should also see a link to download artifacts (video and logs) under "Artifacts". Click on this link to download test artifacts.

The artifacts are organized with one folder per test. In our example, we only have one test called "myFirstTest.test.js". Open this folder to see browser logs in the file "logs_0_${timestamp}.txt" and a video "video_0_${timestamp}.mp4". The 0 in the file names refers to the page index. If your test involved more than one page, there would be corresponding logs and videos for each additional page.

Now let's update our workflow file to also run our tests on a schedule. In the ".github/workflows/qawolf.yml" file, comment in lines 7-9.

name: qawolf on: push: # test every branch # edit below if you only want certain branches tested branches: "*" schedule: # test on schedule using cron syntax - cron: "0 * * * *" # every hour

These lines tell GitHub to run your tests on a schedule specified using cron syntax. The default value is "0 * * * *", which means run every hour on the hour. Update this value if you would like to use a different time interval.

We will change one more thing about our workflow file. GitHub Actions has a storage limit for artifacts, so we don't want to upload them every time. Instead we will only upload logs and videos when the tests fail. Update line 51 from if: always() to if: failure().

# ... - name: Upload Artifacts if: failure() uses: actions/[email protected] with: name: qawolf path: ${{ github.workspace }}/artifacts 

Commit your changes and push them to GitHub.

git add . git commit -m "Run tests on a schedule" git push

Now your smoke tests will run every hour on GitHub Actions!

8. Set up alerts with Slack

The last piece of our pipeline is an alerting system that lets us know when our tests fail. In this tutorial we use Slack because it has a free plan. You can also use a service like PagerDuty, which will have a similar setup process.

via GIPHY

If you do not already have a Slack account and workspace, create them now.

Create Slack webhook

We will now create a Slack webhook, which is a URL that allows us to send Slack messages programmatically. We will make a POST request to this URL when our tests fail.

First we need to create a Slack app, which will be responsible for sending our alert messages. Get started by visiting the Slack API website. In the top right hand corner is a green button to "Create New App".

Click on this button and you will be prompted to name your Slack app and choose a workspace. In our example, we call our app "smoke-tests". After you have filled out the form, click the green "Create App" button.

You should be redirected to your app's page in Slack. Make sure you are on the "Basic Information" page under "Settings". Under "Add features and functionality", there is a link for "Incoming Webhooks". Click on this link.

On the Incoming Webhooks page, click on the toggle to turn on incoming webhooks.

You will then be able to see the "Add New Webhook to Workspace" button at the bottom of the page. Click this button to add a new webhook. We will use this webhook to send a Slack message when our tests fail.

You will then be prompted to choose the channel where your messages will be posted. In our example, we select the "alerts" channel. After choosing your channel, click the green "Allow" button.

You will be redirected to the webhooks page. Under "Webhook URLs for Your Workspace", you now should see your webhook URL.

To test your webhook, copy the code under "Sample curl request to post to a channel". It will look something like the following.

curl -X POST -H 'Content-type: application/json' --data '{"text":"Hello, World!"}' //hooks.slack.com/services/SECRET

Paste this in the command line and press Enter. You will see the message "Hello, World!" posted to the channel you specified.

Send alert when tests fail

Now that we have our Slack webhook, we need to update our GitHub Actions workflow file. We will add a step that makes a POST request to our webhook when the tests fail.

Rather than paste our webhook URL into our workflow file directly, we will add it to our repository secrets. Secrets are encrypted environment variables that store sensitive information. Keeping our webhook URL secret prevents others from seeing it and potentially using it for evil. ?

Add a new secret under your repository settings. Call your secret SLACK_WEBHOOK_URL, and set its value to your Slack webhook URL. The video below provides an example.

Now let's update our workflow file. At the bottom of the ".github/workflows/qawolf.yml" file, add the following lines. These lines tell GitHub to make a POST request to your Slack webhook when your tests fail. We changed the value passed to "text" from "Hello, World!" to "Smoke tests failed!", but you can use whatever message you like.

Note that we do not use the value of our Slack webhook URL directly, but instead replace it with ${{ secrets.SLACK_WEBHOOK_URL }}.

# ... - name: Upload Artifacts if: failure() uses: actions/[email protected] with: name: qawolf path: ${{ github.workspace }}/artifacts # add the following lines - name: Post Slack Message if: failure() run: | curl -X POST -H 'Content-type: application/json' --data '{"text":"Smoke tests failed!"}' ${{ secrets.SLACK_WEBHOOK_URL }}

If you would like to test that your webhook works, throw an error in your test file ".qawolf/myFirstTest.test.js". Then push your changes to GitHub.

test("myFirstTest", async () => { await page.goto("//todomvc.com/examples/react"); await page.click(selectors["0_what_needs_to_b_input"]); await page.type(selectors["1_what_needs_to_b_input"], "create test!"); await page.press(selectors["2_what_needs_to_b_input"], "Enter"); await page.click(selectors["3_input"]); await page.click(selectors["4_button"]); // add this line throw new Error("demogorgon!"); });

Your test will fail, and a message will be posted in Slack. You will also be able to download artifacts.

After you are done testing your webhook, make sure to remove the error from your test code.

9. Conclusion

If you made it this far, congratulations! ?

via GIPHY

In this tutorial we learned about smoke tests and built a smoke testing pipeline. Now you can be your team's smoke testing hero! ?

If your team needs help with QA, or if you just want to chat, please drop me a line at [email protected] ?