How to restart the browser in protractor-cucumber framework or protractor-jasmine

The problem at hand:

https://sqa.stackexchange.com/questions/42235/how-to-restart-browser-in-protractor-cucumber-framework-or-protractor-jasmine

Solution:

You are trying to access an element instance that was created using the previous browser instance. The workflow is as follow,

  1. You imported the page object instance at the start of the spec using require
  2. A browser instant is created in the onPrepare
  3. Using that instance your page object model gets the element object
  4. But on next ‘It’ the browser restarts but the page object instance remains the same
  5. So when you try to interact with the element, you are getting session ID of non-existing browser.

Solution:

As given in your code, you have your page object as a javascript property, than a function

So what you could do is, reinitiate the page object whenever you restart the browser.

This could be done using npm decahe module: https://www.npmjs.com/package/decache

So whenever, you restart the browser reinitiate the module using below command:

//import in top of the spec
var decache = require('decache');
//reinitiate where browser is restarted
decache('../pageobjects/stage1.js');
stage1 = require('../pageobjects/stage1.js');

So your final code:

'use strict';
var decache = require('decache');
let stage1 = require('../pageobjects/stage1.js');

describe('Validate stage 1 and 2 behaviour', function () {
    beforeEach(async function () {        
await browser.waitForAngularEnabled(false);
decache('../pageobjects/stage1.js');
stage1 = require('../pageobjects/stage1.js');
});

    it('Validate that error message in all fields given uploaded {Regression} {Smoke} {Sanity}', async function () {
await stage1.goto()
await stage1.sendValue('hi')
await browser.sleep(5000)
});

Note:

This works even if the page object is defined as a function

For protractor-cucumber add the same in before hook :

you should add the hook in the step definition file itself and not in separate hook.js:

"use strict";
let {Given,Before} = require('cucumber');
let decache = require('decache');
let stage1 = require('../pageobjects/stage1.js');
Before(async function (scenario) {
decache('../pageobjects/stage1.js');
stage1 = require('../pageobjects/stage1.js');
await browser.sleep(4000)
});
 Given('I navigates to google', async() => {
await stage1.goto()
});