How to access step definition variables using hooks.js



  • Hi in the below protractor-cucumber step-definition, I can modify the step definition variable a from before hook:

        "use strict"; 
            let { Given, Before } = require('cucumber');        
            let a=10;
    
        Before(async function (scenario) {
          a=12;  
        });        
        
        Given('I navigates to google', async () => {
          console.log(a)
        });
    
    
    <p>But if I declare before hook in a different file say, hook.js:</p>
    <pre class="lang-js prettyprint-override"><code>    'use strict';
        
        var { After, Before } = require('cucumber');
        
        Before(async function (scenario) {
            let a=12;  
          });
    

    and call it from spec in protractor config:

        cucumberOpts: {
            require: ['./testsuites/test1.js','./commons/hooks.js'],
    ```
    

    The step definition variable a is not getting affected, as the scope of 'a' in hook is local:

    Is there a way to change the step definition variables from hook.js without needing to declare the variable as global?

    Update:

    I tried below code:

    Created world.js

        const { setWorldConstructor } = require('cucumber')
    
    function CustomWorld() {
      this.a=1
    }
    
    setWorldConstructor(CustomWorld)
    
    
    <p><strong>Call it from hooks.js</strong></p>
    <pre class="lang-js prettyprint-override"><code>This prints `CustomWorld { a: 1 }`
    
        'use strict';
        var {  Before } = require('cucumber');
        
        Before(async function (scenario) {
            console.log("hooks")
            console.log(this)
        });
    

    Call the same from step definition:

    This prints empty property `{}`
    
    "use strict";
    console.log("feature head")
    console.log(this)
    let { Given } = require('cucumber');
    
    Given('I navigates to google', async () => {
      console.log("Given nav")
      console.log(this)
    });
    
    
    <p><strong>Update:</strong></p>
    <p><strong>Call the same from step definition:</strong></p>
    <p>Here I removed arrow function and this prints the World object properly'</p>
    <pre class="lang-js prettyprint-override"><code>    "use strict";
        console.log("feature head")
        console.log(this)
        let { Given } = require('cucumber');
        
        Given('I navigates to google', async function() {
          console.log("Given nav")
          console.log(this)
        });
    


  • In CucumberJS you can use a setWorldConstructor where you can create for example a this.context which can we used in each steps and hooks I think.

    For an example code look here: https://github.com/cucumber/cucumber-js/blob/0b2d7e468cf10ecef37749efaddd2dfbea8c7808/features/generator_step_definitions.feature

    Other reads:



Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2