This is error message on a protractor test use protractor http mock:
JavascriptError: javascript error: [$injector:nomod] Module 'httpMock'
is not available! You eit her misspelled the module name or forgot to
load it. If registering a module ensure that you specify the
dependencies as the second argument.
conf.js:
// An example configuration file.
exports.config = {
directConnect: true,
// Selenium server
SeleniumAddress: 'http://localhost:4444/wd/hub',
// Capabilities to be passed to the webdriver instance.
capabilities: {
'browserName': 'chrome'
},
//baseUrl: 'http://develop.garbo.livebranches.com/sv-SE/',
//Framework to use. Jasmine 2 is recommended.
framework: 'jasmine2',
//frameworks: ['mocha', 'jasmine'],
// Spec patterns are relative to the current working directly when
// protractor is called.
//specs: ['testmain.js','testlogin.js'],
//specs: ['testmain.js','testteaPartyList.js','testpositionSearchIndex.js','testpositionList.js'],
specs: ['testlogin.js'],
//Options to be passed to Jasmine.
jasmineNodeOpts: {
defaultTimeoutInterval: 250000
},
mocks: {
dir: '../node_modules/protractor-http-mock',
//dir: 'mocks',
default: []
},
//=====login begin =====
onPrepare: function() {
require("protractor-http-mock").config = {
rootDirectory: '../node_modules/protractor-http-mock/lib',
//rootDirectory: __dirname,
protractorConfig: "conf.js", // name of the config here
};
}
//=====login end========
};
testlogin.js
describe('angularjs homepage', function() {
//browser.ignoreSynchronization = true;
it('should login', function() {
var mock = require('protractor-http-mock');
var todoList;
beforeEach(function() {
var url ='http://dev.etest.com:285/Actor/tbUsers/LoginAndGet';
var req = {Mobile:'14500000006',Password:'123456'};
var rep = {UserId:164,AccountId:328,Token:'328:dc91d536ab424aa0b8d7f1ecaf64c55b',Id:328};
mock([{
request: {
path: url,
method: 'POST',
data:req,
},
response: {
data: rep,
}
}]);
});
afterEach(function() {
mock.teardown();
});
browser.get('http://localhost:2024/daNiuJob/www/ionicWeb/index.html#/login');
console.log('mock='+mock);
element(by.model('data.userName')).sendKeys('14500000006');
element(by.model('data.password')).sendKeys('123456');
var btnlogin = element(by.id('Regist')).element(by.tagName('a'));
expect(browser.getTitle()).toEqual('userlogin');
browser.getTitle().then(function(text){
console.log('title='+text);
});
//cause mock error
expect(mock.requestsMade()).toEqual([
{ url : 'http://dev.etest.com:285/Actor/tbUsers/LoginAndGet', method : 'GET' },
]);
btnlogin.click();
browser.sleep(8000);
});
});
Why can't find httpMock, thank!
note:
C:\Users\HQ-XXX\AppData\Roaming\npm\node_modules\protractor\node_modules\protractor-http-mock
This is path of 'protractor-http-mock'
You should be giving the path of the http-mock module folder and not lib folder inside it. Change your rootDirectory path of protractor-http-mock inside onPrepare() function to -
rootDirectory: 'C:\Users\HQ-XXX\AppData\Roaming\npm\node_modules\protractor\node_modules\protractor-http-mock ',
If at all you need to provide a relative path then change it as below -
rootDirectory: '..\node_modules\protractor-http-mock ',
Hope this helps.
We had the same issue and it was related to the page reloading at the beginning of every spec.
This was caused by a faulty config of html5mode and the browser.get so it did a redirect at the beginning from foo.bar/ to foo.bar/#/ which unloads all injected protractor code.
Related
I'm trying to load test script according to custom argument passed through start command to start intern test.
To do this I'm trying to require the specific test script inside a test but i am getting Attempt to require unloaded module error.
This is my code set up. Can someone help on on this or sugest some alternative work around to make this work.
define(function (require) {
var intern = require('intern');
var AdvalentAutomationTestSuite = require('intern!object');
AdvalentAutomationTestSuite({
name: 'Advalent Automation Test',
'AdvalentTestSets': function () {
return this.remote
.then(function () {
var product = intern.args.product;
var script = 'Automation/TestScripts/FRG/' + product + '-Config';
require(script)
})
},
});
});
Update:
Including intern.js file:
define(function (require) {
var intern = require('intern');
console.log(intern)
return {
proxyPort: 9000,
proxyUrl: 'http://localhost:9000/',
defaultTimeout: 120000,
capabilities: {
'selenium_version': '2.48.2',
},
environments: [
{browserName: 'chrome', version: '48', platform: ['WINDOWS'], chromeOptions: {args: ['start-maximized']}},
],
maxConcurrency: 3,
tunnel: 'NullTunnel',
reporters: [
{id: 'JUnit', filename: 'test-reports/report.xml'},
{id: 'Runner'},
],
Loaders: {
'host-node': 'dojo/dojo',
'host-browser': 'node_modules/dojo/dojo.js'
},
loaderOptions: {
packages: [{name: 'intern-tutorial', location: '.'}]
},
functionalSuites: [
'Automation/TestScripts/FRG/FRG-Config',
],
defaultTimeout: 70000,
excludeInstrumentation: /^(?:tests|node_modules)\//
}
});
You should be fine with the default loader, although as #Troopers points out, it's loaders, not Loaders. The problem is that you're doing a dynamic require with a computed name:
var script = 'Automation/TestScripts/FRG/' + product + '-Config';
require(script)
AMD loaders don't completely support the require(script) syntax since they don't load modules synchronously. When a module is written in CJS-compatibility mode, the loader fakes it by scanning the module code for require calls and then preloading and caching the modules before executing the module code. When the require(script) call is eventually executed, the preloaded module is returned.
When you use a computed module name, the loader can't preload the module being required, so the synchronous require call will fail. To load a module with a computed name you'll need to use the require([ dependency ]) syntax, like:
var script = 'Automation/TestScripts/FRG/' + product + '-Config';
return new Promise(function (resolve) {
require([ script ], resolve);
});
At a higher level, though, it seems odd to be doing this in a test in the first place. It seems like something that should be handled at the module or config levels. For example, assuming 'Automation/TestScripts/FRG/' + product + '-Config' is a functional test suite, the config could simply add that suite to the functionalSuites list if the required command line argument were provided.
You need to specify a loader in your configuration file :
loaders: {
"host-node": "requirejs",
"host-browser": "node_modules/requirejs/require.js"
},
And install the npm package requirejs
The documentation is here
After few hit and trial I managed to make it work by changing my intern.js as follows:
define(function (require) {
var intern = require('intern');
var product = intern.args.product
return {
functionalSuites: [
'Automation/TestScripts/FRG/' + product + '-Config.js',
],
// rest of config code ...
}
});
Please suggest if there's any better way to do this.
Upon starting my server, I'm attempting to utilize the RequireJS optimizer to combine all my RequireJS modules into a single file. Once the optimizer is finished, I am attempting to utilize the modules but it doesn't seem to be working.
var path = require('path');
var fs = require('fs');
var requirejs = require('requirejs');
requirejs.config({
baseUrl: __dirname,
nodeRequire: require
});
requirejs.optimize({
baseUrl: path.join(__dirname, 'foo'),
dir: 'build',
modules: [{
name: 'main',
include: [ 'src/bar' ]
}]
}, function (data) {
console.log(fs.readFileSync(path.join(__dirname, 'build', 'main.js'), 'utf-8'));
var main = requirejs('/build/main.js'));
var bar = requirejs('src/bar');
}, function (error) {
console.log(error);
});
The output from the console.log is the concatenated files as expected, but bar is undefined.
If I run the following script after the previous script, bar is defined.
var requirejs = require('requirejs');
requirejs.config({
baseUrl: __dirname,
nodeRequire: require
});
var main = requirejs('/build/main.js'));
var bar = requirejs('src/bar');
console.log(bar);
Can anyone offer any insight into what may be preventing the first script from working?
Thanks,
Jake
Your path for baseUrl in requirejs.config was wrong. I've also added removeCombined in the optimizer configuration to prevent loading files that have been combined into main.
However, that not all that was needed. You see I also save the value from requirejs.config in r and then I use this r to load the modules. This is the same thing you would do if you used RequireJS contexts: you'd save the value of the requirejs.config call for each context so that you can use one function to load things from one context and the other to load things from the other context. I have to admit I don't know why this makes the code work. It smells like a bug to me.
Another thing I discovered is that requirejs.optimize swallows any exception thrown in its completion callback. This is definitely a bug. If it ha not been swallowing exceptions, you'd have had a better idea of what was going on.
Here is the code:
var path = require('path');
var fs = require('fs');
var requirejs = require('requirejs');
var r = requirejs.config({
baseUrl: path.join(__dirname, 'build'),
nodeRequire: require
});
requirejs.optimize({
baseUrl: path.join(__dirname, 'foo'),
dir: 'build',
// You should do this to make sure that you are not accidentally loading
// files that have *not* been combined.
removeCombined: true,
modules: [{
name: 'main',
include: [ 'src/bar' ]
}]
}, function (data) {
// console.log(fs.readFileSync(path.join(__dirname, 'build', 'main.js'), 'utf-8'));
var main = r('main');
console.log(main);
var bar = r('src/bar');
console.log(bar);
}, function (error) {
console.log(error);
});
I'm trying to implement protractor screenshot reporter for jasmine 2.
But, I'm getting the following error on terminal:
/usr/local/bin/node lib/cli.js example/conf.js
/Users/sadiq/node_modules/protractor/node_modules/q/q.js:155
throw e;
^
TypeError: reporter.beforeLaunch is not a function
at /Users/sadiq/node_modules/protractor/example/conf.js:38:19
at exports.config.beforeLaunch (/Users/sadiq/node_modules/protractor/example/conf.js:37:13)
at Function.promise
(/Users/sadiq/node_modules/protractor/node_modules/q/q.js:682:9)
Process finished with exit code 1
Version Details:
Protractor: v3.1.1;
Jasmine: v2.0.0;
protractor-jasmine2-html-reporter
PFB the conf.js file
// An example configuration file.
var Jasmine2HtmlReporter = require('protractor-jasmine2-html-reporter');
var reporter = new Jasmine2HtmlReporter ({
dest: '/Users/sadiq/node_modules/protractor/test-results',
filename: 'Login.html'
});
exports.config = {
//The address of a running selenium server.
seleniumAddress: 'http://localhost:4444/wd/hub',
// Capabilities to be passed to the webdriver instance.
capabilities: {
'browserName': 'chrome'
},
// Framework to use. Jasmine is recommended.
framework: 'jasmine2',
// Spec patterns are relative to the current working directly when
// protractor is called.
specs: ['login_spec.js'],
// Options to be passed to Jasmine.
jasmineNodeOpts: {
defaultTimeoutInterval: 30000,
showColors: true
},
// Setup the report before any test starts
beforeLaunch: function (){
return new Promise(function(resolve){
reporter.beforeLaunch(resolve);
});
},
onPrepare: function () {
browser.driver.manage().window().setSize(1200, 800);
jasmine.getEnv().addReporter(reporter);
},
// Close the report after all tests finish
afterLaunch: function (exitCode) {
return new Promise(function (resolve) {
reporter.afterLaunch(resolve.bind(this, exitCode));
});
}
};
Usually reporters are set up in onPrepare instead of beforeLaunch:
var Jasmine2HtmlReporter = require('protractor-jasmine2-html-reporter');
onPrepare: function () {
browser.driver.manage().window().setSize(1200, 800);
var reporter = new Jasmine2HtmlReporter ({
dest: '/Users/sadiq/node_modules/protractor/test-results',
filename: 'Login.html'
});
jasmine.getEnv().addReporter(reporter);
},
Being new to JS unit testing and Angular testing in particular, I tried writing my own tests with Jasmine and Karma. After numerous failed attempts at writing my own tests, I decided to step back and check whether everything is working properly, so I copied the example controller and its tests from the Angular Documentation on Unit testing into my project and I am unable to get even that to work.. I feel like a complete idiot that can't even get the copy-pasted code to work..
So here is the controller that I have initialized in the step1Ctrl.js file:
Module is initialized in another file.
var mainApp = angular.module("mainApp");
mainApp.controller('PasswordController', function PasswordController($scope) { $scope.password = ''; $scope.grade = function() {
var size = $scope.password.length;
if (size > 8) {
$scope.strength = 'strong';
} else if (size > 3) {
$scope.strength = 'medium';
} else {
$scope.strength = 'weak';
} }; });
And here's are the tests that live inside step1Ctrl.spec.js:
describe('PasswordController', function() {
beforeEach(module('mainApp'));
var $controller;
beforeEach(inject(function(_$controller_){
// The injector unwraps the underscores (_) from around the parameter names when matching
$controller = _$controller_;
}));
describe('$scope.grade', function() {
var $scope, controller;
beforeEach(function() {
$scope = {};
controller = $controller('PasswordController', { $scope: $scope });
});
it('sets the strength to "strong" if the password length is >8 chars', function() {
$scope.password = 'longerthaneightchars';
$scope.grade();
expect($scope.strength).toEqual('strong');
});
it('sets the strength to "weak" if the password length <3 chars', function() {
$scope.password = 'a';
$scope.grade();
expect($scope.strength).toEqual('weak');
});
});
});
Literally copy-pasted from the documentation.
So the error that I get upon running the tests is:
TypeError: undefined is not a constructor (evaluating '$controller('PasswordController', { $scope: $scope })')
Which tells me that the $controller function in the second beforeEach is failing, as $controller is undefined. So it looks like the first beforeEach doesn't run, or it does but an undefined value gets injected with the inject function.
I am also using browserify, if that matters.
Here is my karma.conf.js, if that helps, as well:
module.exports = function(config) {
config.set({
basePath: '',
frameworks: ['browserify', 'jasmine'],
files: [
'https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.0-beta.1/angular.js',
'https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.15/angular-ui-router.js',
'https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.0-beta.1/angular-mocks.js',
'test/unit/**/*.js'
],
exclude: [
],
preprocessors: {
'app/main.js': ['browserify']
},
reporters: ['progress'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['PhantomJS'],
browserify: {
debug: true,
transform: []
},
plugins: [
'karma-phantomjs-launcher', 'karma-jasmine', 'karma-bro'
],
singleRun: false,
concurrency: Infinity
});
};
I have finally managed to figure out what the problem was. PhantomJS wasn't descriptive with the error messages at all. Apparently, it was failing to instantiate my main Angular module mainApp, because I didn't include some source files for external modules that my main module depends on (like ngAnimate, etc.).
So I switched my testing browser from PhantomJS to Chrome and it actually gave me meaningful errors that quickly pointed in the right direction.
Check whether
The testing framework is installed, The test conditions belongs to the
testing framework you are using.
The "karma.config.js" is configured for the framework you
installed.
Use Browser testing instead of Headless PhantomJS testing to get clear directions.
In most cases above are the errors.
I've been looking at the documentation for protractor and I want to be able to select an array of via a selector of any sort and get the text value of the first one and assert it. No matter what I try with protractor it times out when I try getText() and get().
This is what I'm looking at. Reference
Here is my code:
describe('E2E: Global Scan', function () {
beforeEach(function () {
browser.get('#/dashboard/global-scan');
});
it('should grab all a tags within li tags', function () {
element.all(by.css('li a')).then(function(items) {
expect(items.length).toBeDefined()
expect(items[0].getText()).toBeDefined();
});
var list = element.all(by.css('li a'));
expect(list.length).toBeDefined()
expect(list.get(0).getText()).toBeDefined();
});
});
As you can see I tried both with a then promise function and save the result of element.all to a variable and looping through that. That doesn't work either. What happens is the test just times out.
Failures:
1) E2E: Global Scan should grab all a tags within li tags Message:
Error: Timed out waiting for Protractor to synchronize with the page after 10 seconds. Please see
https://github.com/angular/protractor/blob/master/docs/faq.md
If I try browser.element that starts to return me something. But it still breaks when I use get or getText().
Does anyone have any ideas? Doing what the documentation says doesn't actually work. Do I have a really old version of protractor?
You can increase that with setting protractor config
allScriptsTimeout: timeout_in_millis
Refer the https://github.com/angular/protractor/blob/master/docs/timeouts.md page Waiting for Page Synchronization topic for more info.
I was facing the same issue while doing E2E for Angular Project.
Finally, I configured the protractor.conf.js file and spec.e2e.ts to get rid of "Times Out Waiting For Element
".
protractor.conf.js
const { SpecReporter } = require('jasmine-spec-reporter')
exports.config = {
allScriptsTimeout: 110000,
getPageTimeout: 110000,
specs: [
'./e2e/**/example.e2e-spec.ts',
],
capabilities: {
browserName: 'chrome'
},
directConnect: true,
baseUrl: 'http://localhost:8123/',
framework: 'jasmine',
jasmineNodeOpts: {
showTiming: true,
showColors: true,
includeStackTrace: false,
defaultTimeoutInterval: 600000
},
onPrepare () {
require('ts-node').register({
project: 'e2e/tsconfig.e2e.json'
})
browser.driver.manage().deleteAllCookies();
browser.driver.manage().window().maximize();
jasmine.getEnv().addReporter(new SpecReporter({ spec: { displayStacktrace: true } }));
}
}
example.e2e-spec.ts
import { browser, by, protractor, element, promise, ElementFinder, ElementArrayFinder } from 'protractor';
describe('Test', () => {
var originalTimeout;
beforeEach(() => {
originalTimeout = jasmine.DEFAULT_TIMEOUT_INTERVAL;
jasmine.DEFAULT_TIMEOUT_INTERVAL = 120000;
browser.driver.sleep(3000);
});
afterEach(function () {
jasmine.DEFAULT_TIMEOUT_INTERVAL = originalTimeout;
browser.driver.sleep(5000);
});
it('It should display title and it should login also',() => {
browser.ignoreSynchronization = true;
browser.get('/',5000);
expect(browser.getTitle()).toEqual('TitleExample');
});
});