Protractor - Failed: prop is not defined - javascript

Help please to find an error. I'm learning Protractor and try to create a simple test with Page Object.
//login_pageObject.js
let loginContainer = function() {
this.usernameInput = $("input.login-form-01");
this.passwordInput = $("input#login-form-02");
this.loginBtn = $("input.btn");
this.get = function() {
browser.get("https://www.cosmedicalsupplies.com/login.html");
};
this.setUsername = function(username) {
usernameInput.sendKeys(username);
};
this.setPassword = function(password) {
passwordInput.sendKeys(password);
};
this.clickOnLoginBtn = function() {
loginBtn.click();
};
};
module.exports = new loginContainer();
And
//login.js
let loginPage = require('../page_objects/login_pageObject.js');
describe('login_logout autotests', () => {
beforeEach(() => {
browser.ignoreSynchronization = true;
});
it("should sign in", () => {
loginPage.get();
loginPage.setUsername("test1");
loginPage.setPassword("test2");
loginPage.clickOnLoginBtn();
//expect.....
});
});
So, when I run this code, I have a "Failed: usernameInput is not defined" error. Where is mistake?

You need to refer to it as this.usernameInput.

Related

How to stub a dependency in express middleware (express-validator/mocha/chai/sinon/proxyquire)

**Edit: Re-written with a simple example that works first:
So I've got a test file and 2 modules.
moduleA has a dependency, moduleB
// moduleA.js
const ModuleB = require('./moduleB');
function functionA() {
return 20 + ModuleB.functionB();
};
module.exports = { functionA };
// moduleB.js
const functionB = () => {
return 10;
}
module.exports = { functionB }
My test file stubs out functionB (returned from moduleB) using proxyquire:
const sinon = require('sinon');
const proxyquire = require('proxyquire');
describe('Unit Tests', function() {
it('should work', () => {
const mockedFn = sinon.stub();
mockedFn.returns(30);
const copyModuleA = proxyquire('./moduleA', {
'./moduleB': {
functionB: mockedFn
}
});
console.log(copyModuleA.functionA());
})
});
So it outputs 50 (stubbed functionB 30 + functionA 20)
Now I'm trying to take this example into my code:
moduleA in this case is a file called validation.js. It is dependent on moduleB, in this case a sequelize model, Person, with the function I want to mock: findOne
validation.js exports module.exports = { validateLogin };, a function that calls validate, which returns a function that uses Person.findOne()
So in my mind, as with the simple example, I need to create a stub, point to the validation module in proxyquire, and reference the dependency and its findOne function. Like this:
const stubbedFindOne = sinon.stub();
stubbedFindOne.resolves();
validationModule = proxyquire('../../utils/validation', {
'../models/Person': {
findOne: stubbedFindOne
}
});
This should stub Person.findOne in validation.js. But it doesn't seem to. And I have no idea why.
let validationModule;
describe('Unit Tests', () => {
before(() => {
const stubbedFindOne = sinon.stub();
stubbedFindOne.resolves();
validationModule = proxyquire('../../utils/validation', {
'../models/Person': {
findOne: stubbedFindOne
}
});
})
it.only('should return 422 if custom email validation fails', async() => {
const wrongEmailReq = { body: {email: 'nik#hotmail.com'} };
const res = {
statusCode: 500,
status: (code) => {this.statusCode = code; return this},
};
const validationFn = validationModule.validateLogin();
const wrongEmail = await validationFn(wrongEmailReq, res, ()=>{});
expect(wrongEmail.errors[0].msg).to.be.equal('Custom Authorisation Error');
return;
})
And this is my validation.js file:
const Person = require('../models/Person');
// parallel processing
const validate = validations => {
return async (req, res, next) => {
await Promise.all(validations.map(validation => validation.run(req)));
const errors = validationResult(req);
if (errors.isEmpty()) {
return next();
}
const error = new Error();
error.message = process.env.NODE_ENV === 'development'? 'Validation Failed':'Error';
error.statusCode = !errors.isEmpty()? 422:500;
error.errors = errors.array({onlyFirstError: true});
next(error);
return error;
};
};
const validateLogin = () => {
const validations = [
body('email')
.isString()
// snip
.custom(async (value, {req}) => {
try{
const person = await Person.findOne({ where: { email: value } });
if(!person) return Promise.reject('Custom Authorisation Error');
} catch(err) {
throw err;
}
})
.trim(),
];
return validate(validations);
}
module.exports = {
validateLogin
};
So the code in both the small sample and my app is correct, apart from how I stub the function. It shouldn't resolve or reject anything (I tried both out of desperation). It should return null in order to satisfy the conditional rather than jump to the catch block:
try{
const person = await Person.findOne({ where: { email: value } });
if(!person) return Promise.reject('Custom Authorisation Error');
} catch(err) {
throw err;
}
Hope the simple example helps someone else with proxyquire though

How to mock a function in another function nodejs

Trying to write a unittest for the below module in /utility/sqsThing.js. However I'm having diffuculty mocking the sqs.sendMessage method. Anyone know how I should go about this. I'm using the sinon library, and mocha for running the tests.
The function that I'm trying to unittest utility/sqsThing.js:
const AWS = require('aws-sdk');
AWS.config.update({ region: 'us-east-1' });
const sqs = new AWS.SQS({ apiVersion: '2012-11-05' });
const outputQueURL = 'https:awsUrl';
const SQSOutputSender = (results) => {
const params = {
MessageBody: JSON.stringify(results),
QueueUrl: outputQueURL,
};
// Method that I want to mock
sqs.sendMessage(params, function (err, data) {
if (err) {
console.log('Error');
} else {
console.log('Success', data.MessageId);
}
});
};
My attempt at mocking the sqs.sendMessage method in a unittest sqsThingTest.js:
const sqsOutputResultSender = require('../utility/sqsThing');
const AWS = require('aws-sdk');
const sqs = new AWS.SQS({ apiVersion: '2012-11-05' });
const mochaccino = require('mochaccino');
const { expect } = mochaccino;
const sinon = require('sinon');
describe('SQS thing test', function() {
beforeEach(function () {
sinon.stub(sqs, 'sendMessage').callsFake( function() { return 'test' });
});
afterEach(function () {
sqs.sendMessage.restore();
});
it('sqsOutputResultSender.SQSOutputSender', function() {
// Where the mock substitution should occur
const a = sqsOutputResultSender.SQSOutputSender('a');
expect(a).toEqual('test');
})
});
Running this unittest with mocha tests/unit/sqsThingTest.js however I get:
AssertionError: expected undefined to deeply equal 'test'.
info: Error AccessDenied: Access to the resource https://sqs.us-east-1.amazonaws.com/ is denied..
It looks like the mock did not replace the aws api call. Anyone know how I can mock sqs.SendMessage in my test?
You could use rewire js it is a library that lets you inject mocked properties into your module you want to test.
Your require statement would look something like this:
var rewire = require("rewire");
var sqsOutputResultSender = rewire('../utility/sqsThing');
Rewire will allow you to mock everything in the top-level scope of you sqsThing.js file.
Also you need to return the value of sqs.sendMessage this will remove the issue expected undefined to deeply equal 'test'
Your original file would look the same just with a return statement.
//utility/sqsThing.js
const AWS = require('aws-sdk');
AWS.config.update({ region: 'us-east-1' });
const sqs = new AWS.SQS({ apiVersion: '2012-11-05' });
const outputQueURL = 'https:awsUrl';
const SQSOutputSender = (results) => {
const params = {
MessageBody: JSON.stringify(results),
QueueUrl: outputQueURL,
};
// Method that I want to mock
return sqs.sendMessage(params, function (err, data) {
if (err) {
console.log('Error');
} else {
console.log('Success', data.MessageId);
}
});
};
You would then write your unit test as follows:
//sqsThingTest.js
var rewire = require("rewire");
var sqsOutputResultSender = rewire('../utility/sqsThing');
const mochaccino = require('mochaccino');
const { expect } = mochaccino;
const sinon = require('sinon');
describe('SQS thing test', function() {
beforeEach(function () {
sqsOutputResultSender.__set__("sqs", {
sendMessage: function() { return 'test' }
});
});
it('sqsOutputResultSender.SQSOutputSender', function() {
// Where the mock substitution should occur
const a = sqsOutputResultSender.SQSOutputSender('a');
expect(a).toEqual('test');
})
});
This example returns an object with a property of sendMessage but this could be replaces with a spy.
Rewire Docs
Try moving the declaration of sqsOutputResultSender after you have stubbed the sendmessage function
var sqsOutputResultSender;
const AWS = require('aws-sdk');
const sqs = new AWS.SQS({ apiVersion: '2012-11-05' });
const mochaccino = require('mochaccino');
const { expect } = mochaccino;
const sinon = require('sinon');
describe('SQS thing test', function() {
beforeEach(function () {
sinon.stub(sqs, 'sendMessage').callsFake( function() { return 'test' });
sqsOutputResultSender = require('../utility/sqsThing');
});
afterEach(function () {
sqs.sendMessage.restore();
});
it('sqsOutputResultSender.SQSOutputSender', function() {
// Where the mock substitution should occur
const a = sqsOutputResultSender.SQSOutputSender('a');
expect(a).toEqual('test');
})
});

How to test promises chain using jest?

I have module executer that will be executed on every api request now i am trying to write cases to unit test that executer. I have promise that returns chain that is being executed based on response. I see issue executing promise in test case , any help here to proper test this use case will be apprecaited.
main.ts
export class Executor {
private passedParam: ILogParams = {} as ILogParams;
constructor(public identity: Identity) {
this._ajv = new Ajv();
}
public execute(moduleName: string): (param1, param2) => any {
const self = this;
// getting rid of the tslint issue with Function
return function(params: any, responseCallback: (param: any , param2: any) => any) {
let _mod;
let _httpRequest;
let _params;
Promise.resolve(getApiModule(self.identity, moduleName))
.then((mod: ModuleBase<any, any>) => {
_mod = mod;
mod.ExecStage = ExecStage.Init;
return mod.init(getHttpModule(self.identity), params);
})
.then((httpRequest: HttpRequestBase) => {
_httpRequest = httpRequest;
if (_mod.Response().Summary.Header) {
throw _mod.Response().Summary;
}
return httpRequest;
})
.then(() => {
// empty the error stack
_mod.objErrorHandler.RemoveAllError();
_mod.ExecStage = ExecStage.Before;
return _mod.before(params);
})
.then((params1: any) => {
const _validators = _mod.getValidators();
let _failed: boolean = false;
return params1;
})
.then((params2: any) => {
_params = params2;
_mod.ExecStage = ExecStage.Core;
return _mod.core(_params, _httpRequest);
})
.catch((data: any) => {
const error: IHeader = {} as IHeader;
})
.then((data: any) => {
responseCallback(data, moduleName.substr(moduleName.indexOf('/') + 1));
});
};
}
}
main.spec.ts
import * as sinon from "sinon";
import {ModuleExecutor} from "./main.ts";
import {ExecStage, Identity} from "../../src/ts/common/Enums";
import ValidateRequestSchema from "../../src/ts/validation/requestSchema.js";
describe("ModuleExecuter", () => {
const sandbox = sinon.createSandbox();
afterEach(function afterTests() {
sandbox.restore();
});
let executer;
let executerSpy;
let results;
let stubbedExecutor;
let apiModule;
let _this;
const stubbedExecutorReturnFuction = sandbox.spy(function(args) {
executer = new ModuleExecutor(Identity.node);
executerSpy = executer.execute();
_this = this;
return new Promise(function(resolve) {
// moduleExecutor.execute(params, callback function)
executerSpy(args, function(data) {
resolve(data.Details);
});
});
});
const stubbedExecutorReturn = sandbox.spy(function(args, innerFunc) {
return innerFunc({Details: successResponse});
});
beforeEach(function() {
stubbedExecutor = sandbox.stub(ModuleExecutor.prototype, "execute").callsFake(function() {
return stubbedExecutorReturn;
});
apiModule = new GetAccountBalance();
const execute = sandbox.spy(stubbedExecutorReturnFuction);
results = execute("Payments/accountBalance/GetAccountBalance", {test:"test"});
});
describe("ModuleExecutor", function() {
it('should call ModuleExecutor.execute', function () {
sinon.assert.calledOnce(stubbedExecutor);
});
it('should return a promise', function() {
results.then(function(data) {
expect(data).toBe(successResponse);
});
});
it('should check validate AJV schema', function() {
let _mod;
results.then((mod: ModuleBase<any, any>) => {
_mod = mod;
mod.ExecStage = ExecStage.Before;
const requestSchema = "I" + _mod.__proto__.constructor.name + "Param";
const classSchema = ValidateRequestSchema[requestSchema];
const valid = _this._ajv.validate(classSchema, {test:"test"});
console.log("BOOLEAN>>>>>>>", valid);
expect(valid).toBeTruthy();
});
});
});
});

Test plain javascript file returning different objects

Is it possible to test the code below with Jasmine testing tool or any other npm module like rewire or similar?
const AuthValidatorDumb = require('./src/AuthValidatorDumb');
const AuthValidator = require('./src/AuthValidator');
const config = require('../config');
let instance;
if (!instance) {
if (config.get('auth.enabled')) {
instance = AuthValidator;
} else {
instance = AuthValidatorDumb;
}
}
module.exports = instance;
I've got a variant for testing the code above.Suppose you have:
1) The code for index.js in the question above.
2) AuthValidator.js:
class AuthValidator {}
module.exports = AuthValidator;
3) AuthValidatorDumb.js:
class AuthValidatorDumb {}
module.exports = AuthValidatorDumb;
Here is test/index.spec.js:
const proxyquire = require('proxyquire');
const AuthValidator = require('../src/AuthValidator');
const AuthValidatorDumb = require('../src/AuthValidatorDumb');
describe('auth index', () => {
it('should return AuthValidator', () => {
const configMock = { get: () => 'sth' };
const Instance = proxyquire('../index', {
'../config': configMock,
});
expect(new Instance() instanceof AuthValidator).toBeTruthy();
});
it('should return AuthValidatorDumb', () => {
const configMock = { get: () => undefined };
const Instance = proxyquire('../index', {
'../config': configMock,
});
expect(new Instance() instanceof AuthValidatorDumb).toBeTruthy();
});
});

How to use createSpyObj properly

I am trying to test the getDatabase Version function will pass the query as in to the executeQuery function in the getQueryResult() called by getDatabase.
The code is as follows:
`
var RequestHandler = function () {
this.getQueryResult = function (sQuery) {
this.checkConnection();
try {
return this.conn.executeQuery.apply(this.conn, arguments);
} catch (err) {
this.conn.close();
this.conn = null;
throw "unexpected error, please check application trace files for more information";
}
};
this.getDatabaseVersion = function() {
var query = "select top 1 VERSION from M_DATABASE";
return this.getQueryResult(query)[0].VERSION;
};
}
`
The test case that I wrote:
`
var RHandler = $.import("sap.hana.graph.viewer.XS_Backend.js.lib", "RequestHandler").RequestHandler;
describe ("getDatabaseVersion Tests", function (){
var rHandler = null;
var getQueryResult = jasmine.createSpyObj('getQueryResult', ['conn', 'executeQuery', 'close']);
var conn = jasmine.createSpyObj('conn', ['executeQuery', 'close']);
beforeEach(function() {
rHandler = new RHandler();
rHandler.openConnection();
});
function getAllQueries() {
return getQueryResult.conn.executeQuery.calls.allArgs().join(':::');
}
it('should return the databaseVersion and match the query sent to getQueryResult', function() {
rHandler.getDatabaseVersion();
expect(rHandler.getDatabaseVersion()).toEqual("2.00.030.00.1502184660");
expect(getAllQueries()).toEqual(/select top 1 VERSION from M_DATABASE/i);
});
});
`
But it doesn't work at all. I am approaching in a wrong way. Can anyone guide me or let me know what I am doing wrong.
You need something like that:
var RHandler = $.import("sap.hana.graph.viewer.XS_Backend.js.lib", "RequestHandler").RequestHandler;
describe('RequestHandler', () => {
let rHandler = null;
let connection = null
beforeEach(() => {
connection = jasmine.createSpyObj('conn', ['executeQuery', 'close'])
rHandler = new RHandler();
rHandler.conn = connection;
});
describe('getQueryResult', () => {
beforeEach(() => {
spyOn(rHandler, 'checkConnection');
});
it('should check connection', () => {
rHandler.getQueryResult();
expect(rHandler.checkConnection).toHaveBeenCalled();
});
it('should execute query', () => {
connection.executeQuery.and.returnValue('foo');
const actual = rHandler.getQueryResult('bar', 'baz');
// toHaveBeenCalledWithContext
// https://www.npmjs.com/package/jasmine-spy-matchers
expect(connection.executeQuery).toHaveBeenCalledWithContext(connection, 'bar', 'baz');
// or default toHaveBeenCalledWith
expect(connection.executeQuery).toHaveBeenCalledWith('bar', 'baz');
expect(actual).toBe('foo');
});
it('should throw error', () => {
connection.executeQuery.and.throwError(new Error('some error message'));
expect(() => {
rHandler.getQueryResult('bar', 'baz');
}).toThrow('unexpected error, please check application trace files for more information');
expect(rHandler.conn).toBe(null);
});
});
describe('getDatabaseVersion', () => {
it('should return version', () => {
spyOn(rHandler, 'getQueryResult').and.returnValue([{VERSION: '2.00.030.00.1502184660'}])
const actual = rHandler.getDatabaseVersion();
expect(rHandler.getQueryResult).toHaveBeenCalledWith('select top 1 VERSION from M_DATABASE')
expect(actual).toBe('2.00.030.00.1502184660');
});
});
});

Categories