Getting Invalid Chai property: status error which was working fine - javascript

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
);
});

Related

Getting response, but not seeing it in code, using Google's libraries to call the Places API

I have a React application that calls the Places API through Google's dedicated places library.
The library is imported as such:
<script defer src="https://maps.googleapis.com/maps/api/js?key=<API_KEY>&libraries=places&callback=initPlaces"></script>
The code above is inside /public, in index.html. The initPlaces callback, specified in the URL looks as such:
function initPlaces() {
console.log("Places initialized");
}
To make the actual request, the following code is used:
async function makeGapiRequest() {
const service = new window.google.maps.places.AutocompleteService();
const response = await service.getQueryPredictions({
input: "Verona"
});
console.log(res);
}
For testing purposes, the function is called when the document is clicked:
document.addEventListener("click", () => {
makeGapiRequest();
});
On every request, there is a response coming back. For instance, when the input has the value of Verona, the following response is received, and is only visible in the browser network tab:
{
predictions: [
{
description: "Verona, VR, Italy",
...
},
...
],
status: "OK"
}
Whenever maleGapiRequest is called, even though there is a visible response from the API, the response variable is undefined at the time of logging, and the following error is thrown in the console:
places_impl.js:31 Uncaught TypeError: c is not a function
at places_impl.js:31:207
at Tha.e [as l] (places_impl.js:25:320)
at Object.c [as _sfiq7u] (common.js:97:253)
at VM964 AutocompletionService.GetQueryPredictionsJson:1:28
This code is thrown from the Places library imported in /public/index.html.
Did anyone encounter this error before, or has an idea as to what is the problem? I would like it if the solution was available to me, not the library.
The problem was that I was calling the wrong method. Instead of getQueryPredictions call the getPlacePredictions method. It will return different results, but you can configure it to suite your needs.
Old code:
async function makeGapiRequest() {
const service = new window.google.maps.places.AutocompleteService();
const response = await service.getQueryPredictions({
input: "Verona"
});
console.log(res);
}
New code:
async function makeGapiRequest() {
const service = new window.google.maps.places.AutocompleteService();
const response = await service.getPlacePredictions({
input: "Verona",
types: ["(cities)"]
});
console.log(res);
}

Cannnot Load Workbook in SuiteScript 2.0 N/query Module

I'm trying to use the query module in NetSuite's SuiteScript 2.0 API set, learn how it works so we can try to use it to display data too complex for regular scripted/saved searches. I started off by taking a default template and saving it. In the UI it comes up with results without any issues. I've tried testing with the following code:
require(['N/query']);
var query = require('N/query');
var wrkBk = query.load({ id : "custworkbook1" });
However, all I get is the following error:
Uncaught TypeError: Cannot read property '1' of undefined
at loadCondition (N.js?NS_VER=2021.1.0&minver=60&SS_JS_VERSION=1:17469)
at loadCondition (N.js?NS_VER=2021.1.0&minver=60&SS_JS_VERSION=1:17443)
at loadPostProcess (N.js?NS_VER=2021.1.0&minver=60&SS_JS_VERSION=1:17387)
at Object.loadQuery [as load] (N.js?NS_VER=2021.1.0&minver=60&SS_JS_VERSION=1:17299)
at <anonymous>:1:19
Just for kicks, I thought I'd try the asynchronous version, as well, with the following:
require(['N/query']);
var query = require('N/query');
var wrkBk = null;
query.load.promise({
id : "custworkbook1"
}).then(function(result) {
wrkBk = result;
}).catch(function(err) {
console.log("QUERY LOAD PROMISE ERROR\n\n", err);
})
And like before, got a similar error:
QUERY LOAD PROMISE ERROR
TypeError: Cannot read property '1' of undefined
at loadCondition (N.js?NS_VER=2021.1.0&minver=60&SS_JS_VERSION=1:17469)
at loadCondition (N.js?NS_VER=2021.1.0&minver=60&SS_JS_VERSION=1:17443)
at loadPostProcess (N.js?NS_VER=2021.1.0&minver=60&SS_JS_VERSION=1:17387)
at callback (N.js?NS_VER=2021.1.0&minver=60&SS_JS_VERSION=1:17410)
at myCallback (N.js?NS_VER=2021.1.0&minver=60&SS_JS_VERSION=1:2242)
at XMLHttpRequest.C.f.onload (bootstrap.js:477)
If I run the following code, I get results without errors:
query.listTables({ workbookId : "custworkbook1" });
[
{
"name": "Sales (Invoiced)",
"scriptId": "custview2_16188707990428296095"
}
]
Any idea as to what I'm missing?
I think you're loading the module incorrectly, missing the callback. As per the Help Center, it should be something like:
require(['N/query'], function (query)
{
var wrkBk = query.load({ id : "custworkbook1" });
...do stuff with wrkBk
})
Or for SS2.1:
require(['N/query'], (query) => {
let wrkBk = query.load({ id : "custworkbook1" });
...do stuff with wrkBk
})

Object is not defined when stubbing with Jasmine

I am very new to Jasmine. I am intending to use it for with vanilla javascript project. The initial configuration was a breeze but I am receiving object not defined error while using spyOn.
I have downloaded the version 3.4.0 Jasmine Release Page and added the files 'as is' to my project. I then have changed jasmine.json file accordingly and see the all the example tests passing. However when try spyOn on a private object, I am getting undefined error,
if (typeof (DCA) == 'undefined') {
DCA = {
__namespace: true
};
}
DCA.Audit = {
//this function needs to be tested
callAuditLogAction: function (parameters) {
//Get an error saying D365 is not defined
D365.API.ExecuteAction("bu_AuditReadAccess", parameters,
function (result) { },
function (error) {
if (error != undefined && error.message != undefined) {
D365.Utility.alertDialog('An error occurred while trying to execute the Action. The response from server is:\n' + error.message);
}
}
);
}
}
and my spec class
describe('Audit', function(){
var audit;
beforeEach(function(){
audit = DCA.Audit;
})
describe('When calling Audit log function', function(){
beforeEach(function(){
})
it('Should call Execute Action', function(){
var D365 = {
API : {
ExecuteAction : function(){
console.log('called');
}
}
}
// expectation is console log with say hello
spyOn(D365.API, 'ExecuteAction').and.callFake(() => console.log('hello'));
var params = audit.constructActionParameters("logicalName", "someId", 'someId');
audit.callAuditLogAction(params);
})
})
})
As you can see my spec class does not know about actual D365 object. I was hoping to stub the D365 object without having to inject it. Do I need to stub out whole 365 library and link it to my test runner html?
I got it working after some pondering. So the library containing D365 should still need to be added to my test runner html file. after that I can fake the method call like below,
it('Should call Execute Action', function(){
spyOn(D365.API, 'ExecuteAction').and.callFake(() => console.log('hello'));
var params = audit.constructActionParameters("logicalName", "someId", 'someId');
audit.callAuditLogAction(params);
})
it is now working.

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'
}

AssertionError { state: 'pending' }

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.

Categories

Resources