AssertionError { state: 'pending' } - javascript

I try to use a compilation of differents stacks:
Mocha – test runner
Chai – assertion library
webdriverio – browser control bindings
Selenium – browser abstraction and running factory
PhantomJS – fast headless browser
so i launch a selenium server like this
java -jar selenium-server.jar
and i launch my test like this
mocha test.js -t 10000
Here is my test.js
var webdriverio = require('webdriverio');
var options = { desiredCapabilities: { browserName: 'phantomjs' } };
var client = webdriverio.remote(options);
describe('Test example.com', function(){
before(function(done) {
client.init().url('/* my website */');
done();
//client.pause(5000);
var chai = require('chai');
global.expect = chai.expect;
chai.Should();
});
describe('Check homepage', function(){
it('should wait 3 secondes', function() {
client.pause(3000);
});
it('should see the correct title', function() {
client.waitForValue('#logoHeaderNav', 3000);
client.url('/* my website */');
client.getTitle().should.be.equal('/*my title*/');
});
});
after(function(done) {
client.end();
done();
});
});
and the result i get is :
# mocha test.js -t 10000
Test example.com
Check homepage
✓ should wait 3 secondes
1) should see the correct title
1 passing (108ms)
1 failing
1) Test example.com Check homepage should see the correct title:
AssertionError: expected { state: 'pending' } to equal '/*my title */'
at Context.<anonymous> (test.js:90:35)
any ideas of something i'm doing wrong ??

WebdriverIO commands all return promises, which is what the { state: 'pending' } is in your error message.
To get around this, you'll want to use Chai's "as-promised" plugin. The official site has a page detailing how to get this set up for you.

Try removing the client.waitForValue('#logoHeaderNav', 3000); statement and see if it works.

Related

Getting Invalid Chai property: status error which was working fine

would need bit of help. I have written a code for API Test which is below, but I am getting an error Invalid Chai property: status. Can anyone of you please guide what am I doing wrong. This was working fine till few hours before.
Api is working fine too I have tallied by doing it manually.
import supertest from "supertest";
var chai = require('chai');
import { expect } from 'chai';
chai.use(require('chai-json-schema'));
const request =
supertest("https://graana.rocks/api/");
describe('Area_Details', () => {
it('GET /areadetails', (done) => {
process.env['NODE_TLS_REJECT_UNAUTHORIZED'] = '0';
request.get('area/1921').end((err,res) => {
expect(res).to.have.status(200);
let array1 = Object.entries(res.body);
expect(array1).to.be.a('array');
expect(res.body).to.be.jsonSchema(CheckSchema);
done();
});
});
});
You need the chai-http plugin to be able to do:
expect(res).to.have.status(200);
Reference: https://www.chaijs.com/plugins/chai-http/
From the doc chai-http
The Chai HTTP module provides a number of assertions for the expect and should interfaces.
.status (code) assertion is one of them.
supertest will not provide these assertions for the expect and should interfaces of chai.
See chai-http/blob/4.3.0/lib/http.js#L79
Assertion.addMethod('status', function (code) {
var hasStatus = Boolean('status' in this._obj || 'statusCode' in this._obj);
new Assertion(hasStatus).assert(
hasStatus
, "expected #{act} to have keys 'status', or 'statusCode'"
, null // never negated
, hasStatus // expected
, this._obj // actual
, false // no diff
);
var status = this._obj.status || this._obj.statusCode;
this.assert(
status == code
, 'expected #{this} to have status code #{exp} but got #{act}'
, 'expected #{this} to not have status code #{act}'
, code
, status
);
});

Child process not killed - Node js ( inside Electron js app, windows)

I am trying to stop this command after 4 seconds, but it doesn't stop the child-process
(Running in an electron-js app, windows )
child = child_process.spawn("ping google.com -t", {
encoding: 'utf8',
shell: true
});
child.stdout.on('data', (data) => {
//Here is the output
data=data.toString();
console.log(data)
});
setTimeout(function() {
console.log('Killing Your child', child.pid);
child.kill()
}, 4 * 1000);
the timeout runs after 4 seconds, it logs the message but never stops the process
I tried using tags inside the kill() like "SIGINT" or "SIGKILL"
I tried running without the timeout too...
By looking at the official documentation for child process I have slightly modified your provided example to a bare minimum of what still seems to work for me. Please note that the ping -t flag requires an argument which you didn't provide.
The following worked for me (the program exits after 4 pings) on Node LTS (16.15.1) and the latest version (18.4.0):
const { spawn } = require('child_process');
const child = spawn("ping", ['www.google.com'], {});
child.stdout.on('data', (data) => { console.log(data.toString()); });
setTimeout(() => {
console.log('Killing Your child', child.pid);
child.kill();
}, 4000);
shell: true doesn't work with .kill()
as you can see in the answer from this post:
Try to kill a spawn process with shell true and detached true nodejs
I needed to replace:
child.kill()
with
child_process.spawn("taskkill", ["/pid", child.pid, '/f', '/t']);

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,

Storing global variable in a separate file for Protractor Tests

I am trying to create a separate inventory file for Protractor Test where I can store all the reusable variable to be used by different test scrips. The sample Variable list is called Vars.js and the specs should import the variables from this file and consume those. However, this fails as shown below. Can this approach actually be used for storing reusable variables? Can I actually create a separate inventory file for protractor tests outside of conf.js?
Vars.js has the following content :
"use strict";
exports.config = {
function() {
global.loginMain = 'https://mytestsite.com/auth/login';
global.TestText = 'I am the test Text';
}
};
and the spec file is as follows:
require ('./Vars.js')
require('..\\waitAbsent.js')
require("../node_modules/jasmine-expect/index.js")
describe('Vairables Import Test', function() {
console.log(global.loginMain);
console.log(global.TestText);
browser.get(global.loginMain);
it('Text Validation', function(){
expect(browser.getCurrentUrl()).toEqual('https://mytestsite.com/auth/login')
})
});
The log
[10:55:29] I/local - Selenium standalone server started at http://192.168.1.187:51256/wd/hub
undefined
undefined
Started
(node:17800) [DEP0005] DeprecationWarning: Buffer() is deprecated due to security and usability issues. Please use the Buffer.alloc(), Buffer.allocUnsafe(), or Buffer.from() methods
instead.
F
Failures:
1) Vairables Import Test encountered a declaration exception
Message:
TypeError [ERR_INVALID_ARG_TYPE]: The "url" argument must be of type string. Received type undefined
Stack:
TypeError [ERR_INVALID_ARG_TYPE]: The "url" argument must be of type string. Received type undefined
at Url.parse (url.js:152:11)
at urlParse (url.js:146:13)
at Url.resolve (url.js:661:29)
at Object.urlResolve [as resolve] (url.js:657:40)
at ProtractorBrowser.get (C:\FCPS_I\FCPS\node_modules\protractor\built\browser.js:653:17)
at Suite.<anonymous> (C:\FCPS_I\FCPS\TestBed_Scripts\TestBed.js:10:13)
at Object.<anonymous> (C:\FCPS_I\FCPS\TestBed_Scripts\TestBed.js:5:1)
1 spec, 1 failure
Update: a revised Vars.js where I used params as shown below also return the same failure.
"use strict";
exports.config = {
params: {
loginMain: 'https://dss-esy.insystechinc.com/auth/login',
TestText : 'I am the test Text',
}
};
The below approach should work for you.
conf.js
exports.config = {
framework: 'jasmine',
seleniumAddress: 'http://localhost:4444/wd/hub',
specs: ['app.js'],
onPrepare: async() => {
global.globalVariables = require('./globalVariables');
}
};
app.js
describe('desribe the test', () => {
it('the it', async () => {
console.log(globalVariables.loginMain);
console.log(globalVariables.TestText);
})
})
globalVariables.js
module.exports = {
loginMain :'https://mytestsite.com/auth/login',
TestText : 'I am the test Text'
}

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.

Categories

Resources