Multiple functions with onPrepare in Protractor - javascript

I have a conf.js file in my Protractor test suite.
There was a single onPrepare entry at first but now I wish to add a second.
I'm struggling to get the syntax right so that what follows onPrepare is error free.
Original entry:
onPrepare: function() {
jasmine.getEnv().addReporter(reporter);
},
and the second entry is:
const protractorImageComparison = require('protractor-image-comparison');
browser. protractorImageComparison = new protractorImageComparison(
{
baselineFolder: 'path/to/baseline/',
screenshotPath: 'path/to/save/actual/screenshots/'
}
);
},
}
Do I need to add a second function() above const?

Have you try as below?
A tip: onPrepare is the only one place in protractor conf file you can use the variable: browser, because only when run to this function the browser variable initialize complete.
onPrepare: function() {
jasmine.getEnv().addReporter(reporter);
const protractorImageComparison = require('protractor-image-comparison');
browser.protractorImageComparison = new protractorImageComparison(
{
baselineFolder: 'path/to/baseline/',
screenshotPath: 'path/to/save/actual/screenshots/'
}
);
},

Related

Protractor example test fails when running from command line. cannot read property '$$testability' of unefined

Config file
this is my conf.js file
// An example configuration file.
exports.config = {
directConnect: true,
// Capabilities to be passed to the webdriver instance.
capabilities: {
'browserName': 'chrome'
},
// Framework to use. Jasmine is recommended.
framework: 'jasmine',
// Spec patterns are relative to the current working directory when
// protractor is called.
specs: ['example_spec.js'],
// Options to be passed to Jasmine.
jasmineNodeOpts: {
defaultTimeoutInterval: 30000
}
};
Example Spec.js
is there anything wrong with the code here should i add some type of wait time
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);
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);
expect(todoList.get(2).getText()).toEqual('write a protractor test');
});
});
});
Error Code
this is the error I am getting
This seems to be a common issue with protractor if any one can assist me with a fix to get this test running please do
Thanks
Mike,

Refactored watch task using gulp v4 doesn't work

I'm refactoring my gulpfile now I'm using gulp v4 and am having an issue with gulp watch not running my stylesCompileIncremental function. Any help or pointers would be much appreciated.
My refactoring includes:
Switching to using functions instead of gulp.task
Using series and parallel as per the docs
Exporting public tasks at the bottom of my gulpfile ie exports.stylesWatch = stylesWatch;
Adding callbacks in functions to tell Gulp the function is complete
The code for the affected tasks is as follows (directory paths are stored in package.json file hence pathConfig.ui... values):
// Compile only particular Sass file that has import of changed file
function stylesCompileIncremental(cb) {
sassCompile({
source: getResultedFilesList(changedFilePath),
dest: pathConfig.ui.core.sass.dest,
alsoSearchIn: [pathConfig.ui.lib.resources]
});
cb();
}
// Compile all Sass files and watch for changes
function stylesWatch(cb) {
createImportsGraph();
var watcher = gulp.watch(pathConfig.ui.core.sass.src + '**/*.scss', gulp.parallel(devServReloadStyles));
watcher.on('change', function(event) {
changedFilePath = event;
});
cb();
}
// reload css separated into own function. No callback needed as returning event stream
function reloadCss() {
return gulp.src(generateFilePath)
.pipe($.connect.reload()); // css only reload
}
function devServReloadStyles(cb) {
gulp.series(stylesCompileIncremental, reloadCss);
cb();
}
When I run gulp stylesWatch using my refactored code I get the below output (notice the stylesCompileIncremental task is not run):
So my watch tasking is successfully running but there's something wrong when the devServReloadStyles is run for the stylesCompileIncremental function to not kick in.
The original code before refactoring (when using gulp v3) is below:
// Compile only particular Sass file that has import of changed file
gulp.task('styles:compile:incremental', () => {
return sassCompile({
source: getResultedFilesList(changedFilePath),
dest: pathConfig.ui.core.sass.dest,
alsoSearchIn: [pathConfig.ui.lib.resources]
});
});
// Compile all Sass files and watch for changes
gulp.task('styles:watch', () => {
createImportsGraph();
gulp.watch(
pathConfig.ui.core.sass.src + '**/*.scss',
['devServ:reload:styles']
).on('change', event => changedFilePath = event.path);
});
// Reload the CSS links right after 'styles:compile:incremental' task is returned
gulp.task('devServ:reload:styles', ['styles:compile:incremental'], () => {
return gulp.src(generateFilePath) // css only reload
.pipe($.connect.reload());
});
The original task output when running styles:watch is this:
And this is the sassCompile variable used inside stylesCompileIncremental which I've currently not changed in anyway.
/**
* Configurable Sass compilation
* #param {Object} config
*/
const sassCompile = config => {
const sass = require('gulp-sass');
const postcss = require('gulp-postcss');
const autoprefixer = require('autoprefixer');
const postProcessors = [
autoprefixer({
flexbox: 'no-2009'
})
];
return gulp.src(config.source)
.pipe($.sourcemaps.init({
loadMaps: true,
largeFile: true
}))
.pipe(sass({
includePaths: config.alsoSearchIn,
sourceMap: false,
outputStyle: 'compressed',
indentType: 'tab',
indentWidth: '1',
linefeed: 'lf',
precision: 10,
errLogToConsole: true
}))
.on('error', function (error) {
$.util.log('\x07');
$.util.log(error.message);
this.emit('end');
})
.pipe(postcss(postProcessors))
.pipe($.sourcemaps.write('.'))
.pipe(gulp.dest(config.dest));
};
UPDATE
This is due to an issue with my devServReloadStyles function, although I'm still unsure why. If I change my stylesWatch function to use the original devServ:reload:styles task stylesCompileIncremental gets run.
// Compile all Sass files and watch for changes
function stylesWatch(cb) {
createImportsGraph();
var watcher = gulp.watch(pathConfig.ui.core.sass.src + '**/*.scss', gulp.parallel('devServ:reload:styles'));
watcher.on('change', function(event) {
changedFilePath = event;
});
cb();
}
It would still be good to not use the old task and have this as a function though.
Can anybody tell me why my refactored version doesn't work and have any suggestions as to how this should look?
I've fixed this now.
gulp.series and gulp.parallel return functions so there was no need to wrap stylesCompileIncremental and reloadCss inside another function ie. devServReloadStyles.
As per Blaine's comment here.
So my function:
function devServReloadStyles(cb) {
gulp.series(stylesCompileIncremental, reloadCss);
cb();
}
Can just be assigned to a variable:
const devServReloadStyles = gulp.series(stylesCompileIncremental, reloadCss);
And my stylesWatch task is already calling devServReloadStyles:
// Compile all Sass files and watch for changes
function stylesWatch(cb) {
createImportsGraph();
var watcher = gulp.watch(pathConfig.ui.core.sass.src + '**/*.scss', gulp.parallel(devServReloadStyles));
watcher.on('change', function(event) {
changedFilePath = event;
});
cb();
}
So running gulp stylesWatch now runs the stylesCompileIncremental job (notice how devServReloadStyles doesn't show as it's not a function).

load data from module before test executes

(I asked this question recently and accepted an answer but it's still not what I need.) I really need to create dynamic tests from data loaded from a module. Each item from the array will have it's own describe statement with certain protractor actions. My previous post has an answer that says to use an it statement, but I can't do that because there's too much going on.
My main problem is that the data doesn't get loaded in time for the describe. I had another suggestion to use VCR.js or something similar but I don't think those will work because I'm using a module. Is there a way I can save the data to a separate file and load it in? Would that be a good way to go?
var data = require('get-data'); //custom module here
describe('Test', function() {
var itemsArr;
beforeAll(function(done) {
data.get(function(err, result) {
itemsArr = result; //load data from module
done();
});
})
//error: Cannot read property 'forEach' of undefined
describe('check each item', function() {
itemsArr.forEach(function(item) {
checkItem(item);
});
});
function checkItem (item) {
var itemName = item.name;
describe(itemName, function() {
console.log('describe');
it('should work', function() {
console.log('it');
expect(true).toBeTruthy();
});
});
}
});
UPDATE:
I used Eugene's answer and came up with this. I can't test each individual study how I want because the it statement doesn't fire. Is this problem even solvable??
describe('check each item', function () {
it('should load data', function (done) {
browser.wait(itemsPromise, 5000);
itemsPromise.then(function(itemsArr) {
expect(itemsArr).toBeTruthy();
studyArr = itemsArr.filter(function (item) {
return item.enabled && _.contains(item.tags, 'study');
});
studyCount = studyArr.length;
expect(studies.count()).toEqual(studyCount);
checkItems(studyArr);
done();
});
});
function checkItems (itemsArr) {
itemsArr.forEach(function (item) {
describe(item.id, function () {
console.log('checkItems', item.id);
// doesn't work
it('should work', function (done) {
expect(false).toBeTruthy();
done();
});
});
});
}
});
You're trying to do something that Jasmine does not allow: generating tests after the test suite has started. See this comment on an issue of Jasmine:
Jasmine doesn't support adding specs once the suite has started running. Usually, when I've needed to do this, I've been able to know the list of options ahead of time and just loop through them to make the it calls. [...]
("adding specs" === "adding tests")
The point is that you can generate tests dynamically but only before the test suite has started executing tests. One corollary of this is that the test generation cannot be asynchronous.
Your second attempt does not work because it is trying to add tests to a suite that is already running.
Your first attempt is closer to what you need but it does not work either because describe calls its callback immediately, so beforeAll has not run by the time your describe tries to generate the tests.
Solutions
It all boils down to computing the value of itemsArr before the test suite start executing tests.
You could create a .getSync method that would return results synchronously. Your code would then be something like:
var data = require('get-data'); //custom module here
var itemsArr = data.getSync();
describe('Test', function() {
describe('check each item', function() {
itemsArr.forEach(function(item) {
checkItem(item);
});
});
[...]
If writing .getSync function is not possible, you could have an external process be responsible for producing a JSON output that you could then deserialize into itemsArr. You'd execute this external process with one of the ...Sync functions of child_process.
Here's an example of how the 2nd option could work. I've created a get-data.js file with the following code which uses setTimeout to simulate an asynchronous operation:
var Promise = require("bluebird"); // Bluebird is a promise library.
var get = exports.get = function () {
return new Promise(function (resolve, reject) {
var itemsArr = [
{
name: "one",
param: "2"
},
{
name: "two",
param: "2"
}
];
setTimeout(function () {
resolve(itemsArr);
}, 1000);
});
};
// This is what we run when were are running this module as a "script" instead
// of a "module".
function main() {
get().then(function (itemsArr) {
console.log(JSON.stringify(itemsArr));
});
};
// Check whether we are a script or a module...
if (require.main === module) {
main();
}
Then, inside the spec file:
var child_process = require('child_process');
var itemsArr = JSON.parse(child_process.execFileSync(
"/usr/bin/node", ["get-data.js"]));
describe('Test', function() {
itemsArr.forEach(function(item) {
checkItem(item);
});
function checkItem (item) {
var itemName = item.name;
describe(itemName, function() {
console.log('describe');
it('should work', function() {
console.log('it');
expect(true).toBeTruthy();
});
});
}
});
I've tested the code above using jasmine-node. And the following file structure:
.
├── data.js
├── get-data.js
└── test
└── foo.spec.js
./node_modules has bluebird and jasmine-node in it. This is what I get:
$ ./node_modules/.bin/jasmine-node --verbose test
describe
describe
it
it
Test - 5 ms
one - 4 ms
should work - 4 ms
two - 1 ms
should work - 1 ms
Finished in 0.007 seconds
2 tests, 2 assertions, 0 failures, 0 skipped
Try to use a promise, something like:
var deferred = protractor.promise.defer();
var itemsPromise = deferred.promise;
beforeAll(function() {
data.get(function(err, result) {
deferred.fulfill(result);
});
})
And then:
describe('check each item', function() {
itemsPromise.then(function(itemsArr) {
itemsArr.forEach(function(item) {
checkItem(item);
});
});
});
Another solution I can think of is to use browser.wait to wait until itemsArr becomes not empty.
Is your get-data module doing some browser things with protractor? If so, you will need to set/get itemsArr within the context of the controlFlow. Otherwise it will read all the code in the get-data module, but defer its execution and not wait for it to finish before moving right along to those expect statements.
var data = require('get-data'); //custom module here
var itemsArr;
describe('Test', function() {
beforeAll(function() {
// hook into the controlFlow and set the value of the variable
browser.controlFlow().execute(function() {
data.get(function(err, result) {
itemsArr = result; //load data from module
});
});
});
//error: Cannot read property 'forEach' of undefined
describe('check each item', function() {
// hook into the controlFlow and get the value of the variable (at that point in time)
browser.controlFlow().execute(function() {
itemsArr.forEach(function(item) {
checkItem(item);
});
});
});
function checkItem (item) {
var itemName = item.name;
describe(itemName, function() {
console.log('describe');
it('should work', function() {
console.log('it');
expect(true).toBeTruthy();
});
});
}
});

custom yeoman generator test: creating files

I've got a very simple yeoman generator, watchjs, that has speaker subgenerator. Below is hos it is used:
$ yo watchjs:speaker
You called the watch.js speaker subgenerator.
? Speaker file: data/speakers/speakers.json
? Speaker name: abc
{ file: 'data/speakers/speakers.json', name: 'abc' }
Generated slug is: abc
Trying to add: {
"id": "abc",
"name": "abc"
}
Mainly, there are two prompts: file - which defines the json file where data should be appended to and name - which defines actual data to be added to the file (slightly modified). I'm trying to write a simple yeoman test for this. I've been trying to follow the docs, but I'm failing all the time:
$ npm test
> generator-watchjs#0.0.2 test c:\Users\tomasz.ducin\Documents\GitHub\generator-watchjs
> mocha
Watchjs:speaker
{ file: 'speakers.json', name: 'John Doe' } // <- this is my console.log
1) "before all" hook
0 passing (59ms)
1 failing
1) Watchjs:speaker "before all" hook:
Uncaught Error: ENOENT, no such file or directory 'C:\Users\TOMASZ~1.DUC\AppData\Local\Temp\53dac48785ddecb6dabba402eeb04f91e322f844\speakers.json'
at Object.fs.openSync (fs.js:439:18)
at Object.fs.readFileSync (fs.js:290:15)
at module.exports.yeoman.generators.Base.extend.writing (c:\Users\tomasz.ducin\Documents\GitHub\generator-watchjs\speaker\index.js:43:33)
npm ERR! Test failed. See above for more details.
I can't understand where is the file actually created and where are the tests looking for it... There seems to be used a temporary windows location, but anyway, if all things work properly relative to the path, the file should have been found and it's not. Can't figure out what to do to make tests pass.
The best content of my test file is:
'use strict';
var path = require('path');
var assert = require('yeoman-generator').assert;
var helpers = require('yeoman-generator').test;
describe('watchjs:speaker', function () {
before(function (done) {
helpers.run(path.join(__dirname, '../speaker'))
.withOptions({ 'skip-install': true })
.withPrompts({ 'file': 'speakers.json', 'name': "John Doe" })
.on('end', done);
});
it('creates files', function () {
assert.file([
'speakers.json'
]);
});
});
I'm passing a specific name and file name via prompt.
I've found out that npm test call package.json's mocha command (and that's it). But I'm not an expert in mocha.
I'm using node v0.10.35 on Windows7.
First, you should use absolute paths in your test, so the location of the file is predictable.
My test would look something like this:
'use strict';
var fs = require('fs');
var path = require('path');
var assert = require('yeoman-generator').assert;
var helpers = require('yeoman-generator').test;
describe('watchjs:speaker', function () {
before(function (done) {
var self = this;
var name = 'John Doe';
var testPath = path.join(__dirname, 'temp');
// store in test obejct for later use
this.filePath = path.join(testPath, 'speaker.json');
helpers.run(path.join(__dirname, '../speaker'))
.inDir(testPath)
.withPrompts({ 'file': self.filePath, 'name': name })
.withOptions({ 'skip-install': true })
.on('end', done);
});
it('creates files', function () {
assert.file(this.filePath);
assert.fileContent(this.filePath, /\"id\":.*\"john-doe\"/);
assert.fileContent(this.filePath, /\"name\":.*\"John Doe\"/);
});
});
Second, and not directly related to your question, the test above will on the code in the repo you shared. Like I mentioned in my comment, it throws an error here if the file doesn't already exist.
I would change:
var content = JSON.parse(fs.readFileSync(this.options.file, 'utf8'));
to:
try {
var content = JSON.parse(fs.readFileSync(this.options.file, 'utf8'));
} catch(e) {
content = [];
}
With the change above, the test will pass.

Loading external file from Karma/Jasmine test

I'm trying to accomplish a Jasmine test (using Karma and IntelliJ 13) to validate JSON files. Ideally, my test would simply load a JSON file into a data object, then let me parse through to check for valid formatting and data. I don't need to validate functions before or after, nor do I need to test against a server.
My basic setup is like this:
it("should load an external file", function(){
var asyncCallComplete, result,
_this = this;
// asyncCallComplete is set to true when the ajax call is complete
asyncCallComplete = false;
// result stores the result of the successful ajax call
result = null;
// SECTION 1 - call asynchronous function
runs(function() {
return $.ajax('/test/config.json', {
type: 'GET',
success: function(data) {
asyncCallComplete = true;
result = data;
},
error: function() {
asyncCallComplete = true;
}
});
});
// SECTION 2 - wait for the asynchronous call to complete
waitsFor(function() {
return asyncCallComplete !== false;
}, "async to complete");
// SECTION 3 - perform tests
return runs(function() {
return expect(result).not.toBeNull();
});
}
The problem is that no matter what path I use, I get a 404 error and the file won't load. I've tried loading an external JSON result from a remote server using this test service:
http://date.jsontest.com/
And this works.
My test file is named /test/mySpec.js and my karma.conf.js file is on the root. I have moved around the JSON file to all of these locations with no luck. What am I doing wrong?
UPDATE WITH ANSWER:
Per the answer below, I added this to my karma.conf.js:
// fixtures
{ pattern: 'test/*.json',
watched: true,
served: true,
included: false
}
Then, I wrote my test this way:
var json:any;
it("should load a fixture", function () {
jasmine.getFixtures().fixturesPath = "base/test/"
var f = readFixtures("registration.json");
json = JSON.parse(f);
expect(json).toBeDefined();
})
it("should have a title", function () {
expect(json.title).toNotBe(null);
})
etc...
And it passes.
Are you serving the JSON file via karma.config.js?
You can serve JSON files via fixture:
files: [
// angular
'angular.min.js',
'angular-route.js',
'angular-mocks.js',
// jasmine jquery helper
'jquery-1.10.2.min.js',
'jasmine-jquery.js',
// app
'../../public/js/app.js',
// tests
'*-spec.js',
// JSON fixture
{ pattern: '/test/*.json',
watched: true,
served: true,
included: false }
],
Serving JSON via the fixture is the easiest but because of our setup we couldn't do that easily so I wrote an alternative helper function:
Install
bower install karma-read-json
Usage
Put karma-read-json.js in your Karma files, Example:
files = [
...
'bower_components/karma-read-json/karma-read-json.js',
...
]
Make sure your JSON is being served by Karma, Example:
files = [
...
{pattern: 'json/**/*.json', included: false},
...
]
Use the readJSON function in your tests. Example:
var valid_respond = readJSON('json/foobar.json');
$httpBackend.whenGET(/.*/).respond(valid_respond);
If you are trying to load a HTML file and want to avoid using jasmine-jquery, you may take advantage of the karma-ng-html2js-preprocessor.
In your karma.conf.js :
// generate js files from html templates
preprocessors: {
'resources/*.html': 'ng-html2js'
},
files: [
...
'resources/*.html'
],
plugins: [
...
'karma-ng-html2js-preprocessor'
],
In your jasmine spec :
beforeEach(module('resources/fragment.html'));
var $templateCache;
beforeEach(inject(function (_$templateCache_) {
$templateCache = _$templateCache_;
}));
describe('some test', function () {
it('should do something', function () {
// --> load the fragment.html content from the template cache <--
var fragment = $templateCache.get('resources/fragment.html');
expect(fragment).toBe(...);
});
});
Have you tried simply requiring the json file and storing it as a global variable in your test?
I'm developing an Angular2 project right now (using the Angular CLI), and with this setup it works:
// On the very beginning of the file
let mockConfig = require('./test/config.json');

Categories

Resources