Saturday, November 2, 2019

Writing a Log file in Protractor


We need to write Log using Protractor for better debugging, understand the flow or find out the issue on code.

For that reason we need to follow the below steps,

Step 1:
Need to add the following dependencies on package.json.


        "log4js""5.1.0",
        "log4js-protractor-appender""1.1.2"


Step 2:

Import the following modules in conf.js


var log4js = require('log4js');
var fs = require('fs-extra');


Step 3:

Add the following sections on protractor conf.js file


beforeLaunch:function(){
     if (fs.existsSync('./logs/ExecutionLog.log')) {
         fs.unlink('./logs/ExecutionLog.log')
     }
    log4js.configure({
        appenders: {
            fileLog: { type: 'file'filename: './logs/ExecutionLog.log' },
            console: { type: 'log4js-protractor-appender' }
        },
            categories: {
            file: { appenders: ['fileLog'], level: 'info' },
            another: { appenders: ['console'], level: 'trace' },
            default: { appenders: ['console''fileLog'], level: 'trace' }
            
          }
    });
},




  onPrepare: function() {
    browser.logger = log4js.getLogger('protractorLog4js');
 }

Step 4:

Mention scripts as below in conf.js:

  baseUrl:'https://www.google.com',
  // Spec patterns are relative to the current working directory when
  // protractor is called.
  specs: ['../testsjs/google_spec.js','../testsjs/example_spec.js'],
 
Step 5:

Added logger in test file

    beforeEach(function(){
        
        browser.get(browser.baseUrl)
        browser.logger.info("Testingjs Google");
    })


describe('angularjs homepage'function() {
  it('should greet the named user'function() {
    browser.get('http://www.angularjs.org');

    element(by.model('yourName')).sendKeys('Julie');

    var greeting = element(by.binding('yourName'));

    expect(greeting.getText()).toEqual('Hello Julie!');
  });
  
  describe('todo list'function() {
    var todoList;

    beforeEach(function() {
      browser.get('http://www.angularjs.org');
      todoList = element.all(by.repeater('todo in todoList.todos'));
    });

    it('should list todos'function() {
      expect(todoList.count()).toEqual(2);
      browser.logger.info("Testingjsaaaaaaaaaaaa");
      expect(todoList.get(1).getText()).toEqual('build an AngularJS app');
    });

    it('should add a todo'function() {
      var addTodo = element(by.model('todoList.todoText'));
      var addButton = element(by.css('[value="add"]'));

      addTodo.sendKeys('write a protractor test');
      addButton.click();

      expect(todoList.count()).toEqual(3);
      browser.logger.info("Testingjsaaaaaaaaaaaa111111");
      expect(todoList.get(2).getText()).toEqual('write a protractor test');
    });
  });
});

Step 6:
After executing the test cases logs folder automatically created with in directory structure like below


Every time old logs files are deleted and created the log freshly.