<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Diego Souza</title>
    <description>The latest articles on DEV Community by Diego Souza (@carecone).</description>
    <link>https://dev.to/carecone</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F976157%2F4e65a464-a008-4b2b-bc2f-55d2fb6157e6.png</url>
      <title>DEV Community: Diego Souza</title>
      <link>https://dev.to/carecone</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/carecone"/>
    <language>en</language>
    <item>
      <title>Iniciando em cypress!</title>
      <dc:creator>Diego Souza</dc:creator>
      <pubDate>Fri, 13 Jan 2023 00:50:36 +0000</pubDate>
      <link>https://dev.to/carecone/iniciando-em-cypress-1boo</link>
      <guid>https://dev.to/carecone/iniciando-em-cypress-1boo</guid>
      <description>&lt;h1&gt;
  
  
  Iniciando em cypress
&lt;/h1&gt;

&lt;h3&gt;
  
  
  O que é cypress?
&lt;/h3&gt;

&lt;p&gt;Cypress é uma ferramenta de automação focado em e2e que utiliza Javascript como sua linguagem. Utilizado em automação de Front-end de páginas web, mas possibilitando o seu uso para testes de API.&lt;/p&gt;

&lt;h3&gt;
  
  
  Instalação
&lt;/h3&gt;

&lt;p&gt;Node&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Verificar se o npm está instalado corretamente, podendo verificar a versão instalada: npm -v.&lt;/li&gt;
&lt;li&gt;Verificar a versão do node: node -v.&lt;/li&gt;
&lt;li&gt;Instalar as versões pares do Node, as versões LTS. exemplo: 16.13.1.&lt;/li&gt;
&lt;li&gt;Iniciar o projeto: npm init. Será feita algumas perguntas para criação do package.json.&lt;/li&gt;
&lt;li&gt;Na configuração do package.json, informar 'npx cypress open' no 'test command'&lt;/li&gt;
&lt;li&gt;'npx cypress open' é um executor dos pacotes npm&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Cypress&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;npm i cypress &lt;span class="nt"&gt;--save-dev&lt;/span&gt; 
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Como iniciar o Cypress
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;Existem duas formas de se executar o cypress, a primeira é utilizando 'npm run test' que vai abrir a ferramenta do cypress, e a segunda é utilizando 'npx cypress run' que vai rodar os testes no terminal.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Mesmo seguindo todas as configurações passo a passo, é comum em algumas máquinas ocorrer na primeira execução do Cypress o erro: “Command timed out after 30000 miliseconds”. Para isso, temos duas alternativas:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;Executar novamente, com o comando npm run test ou npx cypress open;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Aumentar esse tempo de verificação na variável VERIFY_TEST_RUNNER_TIMEOUT_MS de 30000 para 100000 no arquivo verify.js que fica no caminho: node_modulescypresslib    asks&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;h3&gt;
  
  
  Pastas
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;fixtures: Utilizada para os arquivos de dados fixos, como mocks que serão utilizados nos testes.&lt;/li&gt;
&lt;li&gt;e2e: Utilizada para os arquivos de testes.&lt;/li&gt;
&lt;li&gt;plugins: Utilizada para arquivos que eu posso criar/editar para modificar ou estender o comportamento interno no Cypress.&lt;/li&gt;
&lt;li&gt;support: Utilizada para arquivos de importação e comandos personalizados que podemos criar dentro do Cypress.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Características positivas do Cypress
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;Execução rápida dos testes.&lt;/li&gt;
&lt;li&gt;Verifica quais navegadores tenho instalado na máquina, facilitando na execução.&lt;/li&gt;
&lt;li&gt;Possibilidade de acompanhar toda a linha do tempo dos testes, como o estado anterior, o que aconteceu após a ação etc.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Principais comandos
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;describe: é uma função que tem 2 parâmetros, o primério é o nome da suite de testes, o segundo é uma função onde eu posso executar qualquer coisa&lt;/li&gt;
&lt;li&gt;beforeEach: é um comando que é executado antes do inicio de cada cenário de testes.&lt;/li&gt;
&lt;li&gt;it: é um item de testes ou cenário de teste.&lt;/li&gt;
&lt;li&gt;.visit: resposável por abrir o link informado.&lt;/li&gt;
&lt;li&gt;.contains: resposável por identificar elementos pelo texto.&lt;/li&gt;
&lt;li&gt;.get: resposável por identificar elementos pela classe, tag, id etc.&lt;/li&gt;
&lt;li&gt;.type: responsável por realizar a ação de escrita.&lt;/li&gt;
&lt;li&gt;.click: responsável por realizar a ação de click.&lt;/li&gt;
&lt;li&gt;.should: responsável por realizar as validações.&lt;/li&gt;
&lt;li&gt;.only: faz com que seja executado somente o cenário que tenha esse comando.&lt;/li&gt;
&lt;li&gt;.on: usado para eventos, como por exemplo windows.alert.&lt;/li&gt;
&lt;li&gt;.request: responsável por estruturar e validar as requests.&lt;/li&gt;
&lt;li&gt;.expect: responsável por realizar as validações.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Pacotes úteis
&lt;/h3&gt;

&lt;p&gt;mochawesome é um gerador de relatório personalizado. Com ele podemos fazer configurações, verificar se o log será gerado em html, json, onde será gerado, qual o formato de data para ser utilizado no nome, o título, dentre outros parâmetros&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;npm i &lt;span class="nt"&gt;-D&lt;/span&gt; mochawesome
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Após a instalação. deverá configurar o arquivo cypress.json&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;&lt;span class="o"&gt;{&lt;/span&gt;
 &lt;span class="s2"&gt;"reporter"&lt;/span&gt;: &lt;span class="s2"&gt;"mochawesome"&lt;/span&gt;,
 &lt;span class="s2"&gt;"reporterOptions"&lt;/span&gt;: &lt;span class="o"&gt;{&lt;/span&gt;
 &lt;span class="s2"&gt;"reportDir"&lt;/span&gt;: &lt;span class="s2"&gt;"cypress/report/mochawesome-report"&lt;/span&gt;,
 &lt;span class="s2"&gt;"overwrite"&lt;/span&gt;: &lt;span class="nb"&gt;true&lt;/span&gt;,
 &lt;span class="s2"&gt;"html"&lt;/span&gt;: &lt;span class="nb"&gt;true&lt;/span&gt;,
 &lt;span class="s2"&gt;"json"&lt;/span&gt;: &lt;span class="nb"&gt;false&lt;/span&gt;,
 &lt;span class="s2"&gt;"timestamp"&lt;/span&gt;: &lt;span class="s2"&gt;"mmddyyyy_HHMMss"&lt;/span&gt;,
 &lt;span class="s2"&gt;"charts"&lt;/span&gt;: &lt;span class="s2"&gt;"false"&lt;/span&gt; ,
 &lt;span class="s2"&gt;"code"&lt;/span&gt;: &lt;span class="s2"&gt;"false"&lt;/span&gt;,
 &lt;span class="s2"&gt;"reporterTitle"&lt;/span&gt;: &lt;span class="s2"&gt;"Automação com cypress"&lt;/span&gt;
 &lt;span class="o"&gt;}&lt;/span&gt;,
 &lt;span class="s2"&gt;"projectId"&lt;/span&gt;: &lt;span class="s2"&gt;"zb9ibc"&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;Não chega a ser um pacote, mas uma funcionalidade do cypress, onde você consegue ter um histórico de testes, relatórios mais detalhados sobre os testes executados. 
Utilizar o comando sempre que for executar os testes informando a key do projeto.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;npx cypress run &lt;span class="nt"&gt;--record&lt;/span&gt; &lt;span class="nt"&gt;--key&lt;/span&gt; &lt;span class="s1"&gt;'key'&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Criar comandos
&lt;/h3&gt;

&lt;p&gt;Criar comandos facilita na criação dos testes, além de eliminar código repetido. Deverá ser criado na pasta support e importar no arquivo index.js.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;Cypress.Commands.add&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;'login'&lt;/span&gt;, &lt;span class="o"&gt;(&lt;/span&gt;nome, senha&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
 cy.get&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;'input[formcontrolname="userName"]'&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt;.type&lt;span class="o"&gt;(&lt;/span&gt;nome&lt;span class="o"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
 cy.get&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;'input[formcontrolname="password"]'&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt;.type&lt;span class="o"&gt;(&lt;/span&gt;senha&lt;span class="o"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
 cy.contains&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;'button'&lt;/span&gt;, &lt;span class="s1"&gt;'login'&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt;.click&lt;span class="o"&gt;()&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="o"&gt;})&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Testes de API
&lt;/h3&gt;

&lt;p&gt;Também é possível realizar os testes de API, a sintaxe e as validações são bem tranquilas e parecidas com as que temos no mercado.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt; addUser&lt;span class="o"&gt;()&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
 &lt;span class="k"&gt;return &lt;/span&gt;cy.request&lt;span class="o"&gt;({&lt;/span&gt;
 method: &lt;span class="s2"&gt;"POST"&lt;/span&gt;,
 url: &lt;span class="s2"&gt;"usuarios"&lt;/span&gt;,
 body: payloadAddUser,
 failOnStatusCode: &lt;span class="nb"&gt;false&lt;/span&gt;,
 &lt;span class="o"&gt;})&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
 &lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt; it&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"Cadastrado com sucesso"&lt;/span&gt;, &lt;span class="o"&gt;()&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
 Login.loginAdm&lt;span class="o"&gt;()&lt;/span&gt;.then&lt;span class="o"&gt;((&lt;/span&gt;token&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
 POSTProduto.addProduct&lt;span class="o"&gt;(&lt;/span&gt;token.body.authorization&lt;span class="o"&gt;)&lt;/span&gt;.then&lt;span class="o"&gt;((&lt;/span&gt;response&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
 expect&lt;span class="o"&gt;(&lt;/span&gt;response.status&lt;span class="o"&gt;)&lt;/span&gt;.to.eq&lt;span class="o"&gt;(&lt;/span&gt;201&lt;span class="o"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
 expect&lt;span class="o"&gt;(&lt;/span&gt;response.body.message&lt;span class="o"&gt;)&lt;/span&gt;.to.eq&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"Cadastro realizado com sucesso"&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
 DELETEProduto.deleteProduct&lt;span class="o"&gt;(&lt;/span&gt;
 response.body._id,
 token.body.authorization
 &lt;span class="o"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
 &lt;span class="o"&gt;})&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
 &lt;span class="o"&gt;})&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
 &lt;span class="o"&gt;})&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Proteger dados sensíveis
&lt;/h3&gt;

&lt;p&gt;É possível guardar configurações nas próprias variáveis de ambiente do cypress, como o cypress.json, porém, ele é um arquivo que precisamos enviar para o repositório. Vamos utilizar o cypress.env.json, que também é um arquivo de configuração, mas que não precisamos enviar para nosso repositório, deixando-o no gitignore.&lt;/p&gt;

&lt;h3&gt;
  
  
  Boas práticas
&lt;/h3&gt;

&lt;p&gt;Evitar flaky tests: São testes que ocorrem erros de forma aleatória, não necessariamente são falhas. Exemplo: era esperada que a request fosse realizada em 3 segundos, mas demorou 5, não quer dizer que houve uma falha, mas sim uma demora que pode ou não acontecer.&lt;/p&gt;

&lt;p&gt;Definir uma baseurl&lt;/p&gt;

&lt;p&gt;Utilizar variáveis de ambiente para dados sensíveis&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;cy.login&lt;span class="o"&gt;(&lt;/span&gt;Cypress.env&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;'userName'&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt;, Cypress.env&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;'password'&lt;/span&gt;&lt;span class="o"&gt;))&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Utilizar {log: false} para dados sensíveis&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;&lt;span class="nb"&gt;type&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;senha, &lt;span class="o"&gt;{&lt;/span&gt;log: &lt;span class="nb"&gt;false&lt;/span&gt;&lt;span class="o"&gt;})&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;stub: muito útil para 'mockar' um status esperado.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;cy.intercept&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;'POST'&lt;/span&gt;, &lt;span class="sb"&gt;`&lt;/span&gt;https://serverest.dev/&lt;span class="sb"&gt;`&lt;/span&gt;, &lt;span class="o"&gt;{&lt;/span&gt;
 statusCode: 400
 &lt;span class="o"&gt;})&lt;/span&gt;.as&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;'stubPost'&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt;
adicionar &lt;span class="nb"&gt;wait &lt;/span&gt;no cenário&lt;span class="o"&gt;(&lt;/span&gt;it&lt;span class="o"&gt;)&lt;/span&gt; para que o teste aguarde a interceptação
cy.wait&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;'@stubPost'&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;mock: muito útil quando queremos saber se o endpoint vai ser chamado corretamente, se os parâmetros esperados estão corretos etc.&lt;/p&gt;

</description>
      <category>cypress</category>
      <category>test</category>
      <category>automation</category>
    </item>
  </channel>
</rss>
