<?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>Forem: Sehani Chathurangi</title>
    <description>The latest articles on Forem by Sehani Chathurangi (@sehani_chathurangi).</description>
    <link>https://forem.com/sehani_chathurangi</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%2F2909863%2F7f7e7e1b-e665-4067-8ff3-565a688aa50f.jpg</url>
      <title>Forem: Sehani Chathurangi</title>
      <link>https://forem.com/sehani_chathurangi</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://forem.com/feed/sehani_chathurangi"/>
    <language>en</language>
    <item>
      <title>Reusing Dynamic Values in Cypress Tests: Store Once, Reuse Anywhere</title>
      <dc:creator>Sehani Chathurangi</dc:creator>
      <pubDate>Fri, 11 Jul 2025 03:54:11 +0000</pubDate>
      <link>https://forem.com/cypress/reusing-dynamic-values-in-cypress-tests-store-once-reuse-anywhere-3e4m</link>
      <guid>https://forem.com/cypress/reusing-dynamic-values-in-cypress-tests-store-once-reuse-anywhere-3e4m</guid>
      <description>&lt;p&gt;In test automation, maintaining and reusing state between test cases is essential for creating efficient, end-to-end workflows. When writing Cypress tests that interact with APIs, it's common to receive dynamic data from a response—such as an ID, token, or reference number—that you'll need to use in a later request. Instead of hardcoding or repeating logic, Cypress allows you to &lt;strong&gt;store these values temporarily&lt;/strong&gt; during the test run and reuse them wherever needed.&lt;/p&gt;

&lt;p&gt;Let’s explore how to do this in a clean and efficient way.&lt;/p&gt;

&lt;h2&gt;
  
  
  Why Store Values Dynamically?
&lt;/h2&gt;

&lt;p&gt;Many real-world scenarios involve multi-step processes where the output of one step is the input for the next. For instance:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;A request may return an identifier (id) that’s required for the next API call.&lt;/li&gt;
&lt;li&gt;A system may provide an access token that must be included in subsequent headers.&lt;/li&gt;
&lt;li&gt;You might need to retrieve the status of a resource using a previously returned reference.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;By reusing these variables, you:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Reduce redundancy: Avoid recreating the same data in every test.&lt;/li&gt;
&lt;li&gt;Improve performance: Skip repetitive setup steps.&lt;/li&gt;
&lt;li&gt;Mimic real-world workflows: Simulate multi-step user journeys.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  01.Use Cypress.env() to Store and Reuse Data
&lt;/h2&gt;

&lt;p&gt;Cypress provides a convenient way to store values in memory using Cypress.env() during a test run.&lt;/p&gt;

&lt;h3&gt;
  
  
  Store the Value
&lt;/h3&gt;

&lt;p&gt;When you receive a value from an API response, you can store it like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;cy.request('POST', 'your-api-url', requestBody).then((response) =&amp;gt; {
  const dynamicId = response.body.id;
  Cypress.env('dynamicId', dynamicId); // Save it temporarily
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Reuse It in Another Request
&lt;/h3&gt;

&lt;p&gt;You can then access that value in a later test step:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;cy.request({
  method: 'GET',
  url: `your-api-url/${Cypress.env('dynamicId')}`,
  headers: {
    Authorization: `Bearer yourAccessToken`,
  },
}).then((response) =&amp;gt; {
  expect(response.status).to.eq(200);
  // more assertions
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Example with Tokens&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Here’s how to store an access token received from an authorization request:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;cy.request('POST', 'token-url', credentials).then((response) =&amp;gt; {
  const token = response.body.access_token;
  Cypress.env('accessToken', token); // Stored in memory
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Use it later:&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;cy.request({
  method: 'GET',
  url: 'api/secure-data',
  headers: {
    Authorization: `Bearer ${Cypress.env('accessToken')}`, // Used here
  },
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  02.Using Test-Specific Variables
&lt;/h2&gt;

&lt;p&gt;For data needed only within a single test file, use closures (e.g., let variables).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Example: Reusing a Resource ID&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;describe('Reusing ResourceID Tests', () =&amp;gt; {
  let resourceId; // Accessible across all tests in this describe block
  it('Creates a Resource', () =&amp;gt; {
    cy.request('/resources', { method: 'POST' }).then((response) =&amp;gt; {
      resourceId = response.body.id; // Assign ID
    });
  });
  it('Validates the Resource', () =&amp;gt; {
    cy.request(`/resources/${resourceId}`).then((response) =&amp;gt; {
      expect(response.status).to.eq(200);
    });
  });
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  03. External Storage (Files, Databases)
&lt;/h2&gt;

&lt;p&gt;For cross-suite or cross-run persistence, save data to files (e.g., JSON) or databases. Use this sparingly, as it introduces external dependencies.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Good Practices&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Use Cypress.env() for temporary values within the same test suite.&lt;/li&gt;
&lt;li&gt;Do not use Cypress.env() as a way to persist values between test files.&lt;/li&gt;
&lt;li&gt;Store static configuration in cypress.env.json, but store dynamic values using Cypress.env() at runtime.&lt;/li&gt;
&lt;li&gt;Clean Up State: Delete test data after runs (e.g., in after hooks).&lt;/li&gt;
&lt;li&gt;Avoid Hardcoding Values: Use environment variables or configuration files for URLs, keys, etc.&lt;/li&gt;
&lt;li&gt;Handle Asynchronous Flows: Use cy.wait() or retry logic if systems need time to process data.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Summary
&lt;/h2&gt;

&lt;p&gt;Storing dynamic data during test execution helps avoid hardcoding and keeps your Cypress tests clean and reliable. By leveraging Cypress environment variables, closures, or external storage, you can build robust test suites that minimize redundancy and maximize efficiency. Always prioritize clarity and maintainability—use descriptive variable names and document shared state dependencies. This approach improves test reusability, enhances readability, and supports more complex workflows in your automation suite.&lt;/p&gt;

&lt;p&gt;👉 For more articles like this, visit my site: &lt;a href="https://careersuccesso.com/" rel="noopener noreferrer"&gt;https://careersuccesso.com/&lt;/a&gt;&lt;/p&gt;

</description>
      <category>cypress</category>
      <category>testing</category>
      <category>automation</category>
      <category>qa</category>
    </item>
    <item>
      <title>Mastering Test Flow Control with Cypress.stop()</title>
      <dc:creator>Sehani Chathurangi</dc:creator>
      <pubDate>Tue, 29 Apr 2025 15:18:08 +0000</pubDate>
      <link>https://forem.com/cypress/mastering-test-flow-control-with-cypressstop-1aph</link>
      <guid>https://forem.com/cypress/mastering-test-flow-control-with-cypressstop-1aph</guid>
      <description>&lt;p&gt;Cypress is a powerful tool for end-to-end testing, but sometimes you need to halt execution immediately when a critical failure occurs. Enter Cypress.stop(). This command stops all test execution, ensuring you avoid cascading failures or wasted resources when a prerequisite fails. Let’s explore how to use it effectively. When working with automated tests in Cypress, efficiency is everything—especially when you're running large test suites across multiple environments or CI pipelines. That’s where Cypress's Cypress.stop() method becomes incredibly useful.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;What is Cypress.stop()?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Cypress.stop() halts the Cypress Test Runner mid-execution. It’s a manual switch to stop running &lt;strong&gt;any remaining tests&lt;/strong&gt; in the current spec file.&lt;/p&gt;

&lt;p&gt;It can be incredibly handy in situations like:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;When an essential precondition fails (e.g., token generation, environment setup)&lt;/li&gt;
&lt;li&gt;When you want to stop on the &lt;strong&gt;first failure&lt;/strong&gt;
&lt;/li&gt;
&lt;li&gt;To prevent redundant test execution during debugging or early failure diagnosis&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Syntax&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Cypress.stop()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Example Scenario: Stop Test Run on Token Generation Failure&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Let’s say you’re working on API tests.&lt;/p&gt;

&lt;p&gt;In this API test, Cypress.stop() is used to halt execution if an access token can’t be generated. Without this token, other tests verifying are meaningless. Here’s the breakdown:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;it('Generates an Access Token', () =&amp;gt; {
  cy.request({
    method: 'POST',
    url: `${Cypress.env('baseUrl')}`,
    headers: {
      'subscription-Key': `${Cypress.env('subscriptionKey')}`,
      Authorization:
        'Basic ' +
        btoa(
          `${Cypress.env('apiUser')}:${Cypress.env('apiKey')}`
        ),
    },
    failOnStatusCode: false,
  }).then((response) =&amp;gt; {
    if (response.status !== 200 || !response.body.access_token) {
      cy.log('Access token generation failed!');
      Cypress.stop(); //Stop remaining tests in the file
    }
    cy.log(‘Access token generated successfully');
    Cypress.env('accessToken', response.body.access_token);
  });
});
// ... other tests that depend on the access token
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Stop Tests After Any Failure&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;If you want to &lt;strong&gt;automatically stop the test run on any failure&lt;/strong&gt;, add this to your automation script:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;afterEach(function () {
  if (this.currentTest.state === 'failed') {
    Cypress.stop();
  }
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Behavior Differences: cypress run vs cypress open&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;cypress run (CI mode):&lt;/strong&gt;Cypress.stop() halts execution of the current spec file, but the app continues running and uploads all test results.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fj2smcyew5z6grg46pniu.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fj2smcyew5z6grg46pniu.png" alt="cypress run (CI mode)" width="800" height="166"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;cypress open (Interactive mode):&lt;/strong&gt; Cypress will stop executing tests but keep the Test Runner open for inspection.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F07f7swt0fzq5p2v65hse.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F07f7swt0fzq5p2v65hse.png" alt="cypress open (Interactive mode)" width="800" height="204"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Why This Works&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Fail-Fast Principle: The test suite stops immediately on token failure, avoiding false negatives in later steps.&lt;/li&gt;
&lt;li&gt;Clear Diagnostics: Logs the failure and stops execution, making debugging easier.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;When to Use Cypress.stop() vs. cy.skip()&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Cypress.stop():&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Nuclear option: Stops ALL tests.&lt;/li&gt;
&lt;li&gt;Use when no further tests can proceed (e.g., missing tokens, broken environments).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;cy.skip():&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Skips a single test or block.&lt;/li&gt;
&lt;li&gt;Use when a test is conditionally irrelevant (e.g., a feature flag is off).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Cypress.stop() is simple but powerful for controlling your test flow when you know something has gone wrong. It's especially useful during development or in CI pipelines to avoid wasting resources.&lt;/p&gt;

&lt;p&gt;Cypress.stop() is your emergency brake for tests. By using it in scenarios like failed logins, broken API handshakes, or missing environment variables, you keep your test results clean and actionable. Pair it with robust error logging, and you’ll streamline your debugging process while saving time and resources.&lt;/p&gt;

</description>
      <category>cypress</category>
      <category>automation</category>
      <category>testing</category>
      <category>softwaretesting</category>
    </item>
  </channel>
</rss>
