AssertionError: expected [Function] to throw Error No events were emitted - chai

I am trying to test if a modifier in my smart contract is throwing an error.
My Smart contract funtion and modifier looks like this
function getPermissionedRegions(string memory _patientId) public view
onlyPatient(_patientId) returns(string[] memory) {
return patients[_patientId].permissionedRegions;
}
modifier onlyPatient(string memory _patientId) {
require(patients[_patientId].addr == msg.sender);
_;
}
My test looks like this:
it("getPermissionnedRegions throws an error when called by anybody else but the patient", async function () {
var expect = require('chai').expect;
expect(() => {
instance.getPermissionedRegions.bind(instance, pat_gbg_kungalv, { from: pat_boras_account })
}).to.throw(Error, "Function called by unauthorized actor");
});
I am getting the following error:
AssertionError: expected [Function] to throw Error
After searching for a bit on Stack Overflow I founf the bind() function should help with this but I am still stuck. I would appreciate any help!

Related

keyv iterator not a fucntion error in npmjs keyv library

I'm using https://www.npmjs.com/package/keyv
I'm able to access individual items using key.get, but Im unable to iterator through all items.
In the below piece of code, test is printed correctly, but im unable to access keyv.iterator.
async function testReadDB()
{
let keyv = new Keyv('sqlite://test.sqlite');
test = await keyv.get("test_key")
console.log(test)
try {
for (const [key, value] of keyv.iterator()) {
console.log(key, value);
};
}
catch (e) {
console.log(e.message)
}
}
Error:
keyv.iterator is not a function or its return value is not iterable

how to use expo-sqlite execute sql with typescript?

Hi all I want to use expo-sqlite to transaction object to execute an sql statement.
However, I got a problem in define the return value of the error function.
Here is the example code:
tx.executeSql(
// sql statement (ok)
"...",
// input arguments (ok)
[...],
// success case: since I use it in a promise, so I use: resolve(...) (ok)
() => {
resolve()
},
// failed case: I want to reject it, use reject()
// But I got an Error here! (Wrong!!!)
// Here ask me to return a boolean value, but how??? true or false???
(_, err) => {
reject(err) // not enough???
}
)
From the type definition file, I know, I need to return a boolean value for the error callback function, but which one? true or false???
Do you have some idea how to do it???
PS. Here is official doc about the expo-sqlite: https://docs.expo.io/versions/latest/sdk/sqlite/
I don't know why the error callback function does need a return type of boolean. Since we resolve/reject the promise anyways I think we can savely ignore the return type.
Below you can find my typescript synchronous example:
export const fetchTypeSaveSql = async <T>(sqlStatement: string, args: any[] | undefined): Promise<T[]> => {
return new Promise((resolve) => {
db.transaction(tx => {
tx.executeSql(
sqlStatement, args,
(_, result) => {
resolve(Array.from(result.rows as any) as T[])
},
(_, error): boolean => {
console.warn(error)
resolve([])
return false
})
})
})
}
The return type of SQLStatementErrorCallback is boolean (and not void) because it's used to indicate whether the error was handled or not.
If the error is handled (ie return true), the whole transaction doesn't fail. If it's not handled (ie return false), then it does. You should only return true if you've been able to suitably recover from the error.
Remember that executeSql is only used within a transaction (which is created via db.transaction or db.readTransaction). A transaction accepts it's own success and error callbacks.
You can check the this in the source code by working backwards from this: https://github.com/nolanlawson/node-websql/blob/7b45bf108a9cffb1c7e16b9a7dfec47be8361850/lib/websql/WebSQLTransaction.js#L64-L68
if (batchTask.sqlErrorCallback(self, res.error)) {
// user didn't handle the error
self._error = res.error;
return onDone();
}

error handling in angular 5, catch errors from backend api in frontend

I need advise for handling errors in front-end of web application.
When I call a service to get the community according to community in web app, I want it to catch an error. For example for catching errors like 404.
There is a service for getting community according to id provided.
getCommunity(id: number) {
return this.http.get(`${this.api}/communities/` + id + ``);
}
that is called in events.ts file
setCommunityBaseUrl() {
this.listingService.getCommunity(environment.communityId).subscribe((data: any) => {
this.communityUrl = data.url + `/` + data.domain;
});
}
The id is provided in environment. Let's say there are 20 communities in total. When I provide id = 1 the events according to community = 1 appears.
export const environment = {
production: ..,
version: 'v2',
apiUrl: '...',
organization: '...',
websiteTitle: '...',
communityId: 1,
googleMapsApiKey: '...'
};
The problem is that when I provide id = null all community events are occurring | all events list in the backend is occurring.
Please, help ^^
When you subscribe you subscribe with an Observer pattern. So the first function you pass in
.subscribe(() => {} );
fires when the Observable calls .next(...)
and after that you can provide another function which will fire whenever the Observable calls .error(...)
so
.subscribe(() => {}, (error) => { handleTheError(error); } );
The this.http.get(...); returns an Observable which will fire the .error(...) on http error
We also know that this.http.get(...) completes or "errors" and it's not an endless one (a one that never completes). So you can make it a promise and manipulate on it promise like.
async getMeSomething(...) {
try {
this.mydata = await this.http.get(...).toPromise();
}
catch(error) {
handleTheError(error)
}
}
But what I really recommend is to use Swagger for your backend and then generate the API Client class with NSwagStudio so you don't have to write the client manually or adjust it or deal with error catching. I use it all the time and it saves us an enormous amount of time
Because you are using ".subscribe" you can create your own error handler and catch the errors like this, directly on the method.
This is an example on how you can use this:
constructor(
private _suiteAPIService: SuitesAPIService,
private _testcaseService: TestcaseService,
public _tfsApiService: TfsApiService,
private _notificationService: NotificationService) { }
errorHandler(error: HttpErrorResponse) {
return observableThrowError(error.message || "Server Error")
}
public something = "something";
GetTestcasesFromSuiteSubscriber(Project, BuildNumber, SuiteId) {
this._suiteAPIService.GetTestResults(Project, BuildNumber, SuiteId).subscribe(
data => {
console.log(data);
this._testcaseService.ListOfTestcases = data;
//Notofication service to get data.
this._notificationService.TestcasesLoaded();
},
error => {
//Here we write som error
return this.something;
}
);
}

Aborted upload causes Sails js/Skipper to crash

Ref: https://github.com/balderdashy/skipper/issues/49
Adapter: skipper-gridfs
Basic controller code:
req.file('fileTest')
.upload({
// You can apply a file upload limit (in bytes)
maxBytes: maxUpload,
adapter: require('skipper-gridfs'),
uri: bucketConnect,
saveAs : function (__newFileStream,cb) {
cb(null, __newFileStream.filename);
}
}, function whenDone(err, uploadedFiles) {
if (err) {
var error = { "status": 500, "error" : err };
return res.serverError(error);
}else {
I have a jQuery-File-Upload client ( https://blueimp.github.io/jQuery-File-Upload/ ) impementing the "cancel" procedure by using jqXHR abort described here (https://github.com/blueimp/jQuery-File-Upload/wiki/API ):
$('button.cancel').click(function (e) {
jqXHR.abort();
});
After the client aborts, the server crashes with the following message:
events.js:72
throw er; // Unhandled 'error' event
^
Error: Request aborted
at IncomingMessage.onReqAborted (.../node_modules/sails/node_modules/skipper/node_modules/multiparty/index.js:175:17)
at IncomingMessage.EventEmitter.emit (events.js:92:17)
at abortIncoming (http.js:1911:11)
at Socket.serverSocketCloseListener (http.js:1923:5)
at Socket.EventEmitter.emit (events.js:117:20)
at TCP.close (net.js:466:12)
I've used try/catch but it didn't work, the server crashes anyway.
I am not sure if this is a Skipper issue or a Multiparty issue -- my knowledge stops here ( https://github.com/andrewrk/node-multiparty/blob/master/index.js ):
function onReqAborted() {
waitend = false;
self.emit('aborted');
handleError(new Error("Request aborted"));
}
function onReqEnd() {
waitend = false;
}
function handleError(err) {
var first = !self.error;
if (first) {
self.error = err;
req.removeListener('aborted', onReqAborted);
req.removeListener('end', onReqEnd);
if (self.destStream) {
self.destStream.emit('error', err);
}
}
cleanupOpenFiles(self);
if (first) {
self.emit('error', err);
}
}
At first I thought this was the way the jqXHR request was aborted, but it seems to be a generic Skipper issue on aborted uploads, since the simple act of closing the tab during an upload will crash the server (different message):
_stream_writable.js:233
cb(er);
^
TypeError: object is not a function
at onwriteError (_stream_writable.js:233:5)
at onwrite (_stream_writable.js:253:5)
at WritableState.onwrite (_stream_writable.js:97:5)
at Writable.<anonymous> (.../node_modules/skipper-gridfs/index.js:179:25)
at Writable.g (events.js:180:16)
at Writable.EventEmitter.emit (events.js:117:20)
at PassThrough.<anonymous> (.../node_modules/skipper-gridfs/index.js:194:36)
at PassThrough.g (events.js:180:16)
at PassThrough.EventEmitter.emit (events.js:117:20)
at .../node_modules/sails/node_modules/skipper/standalone/Upstream/prototype.fatalIncomingError.js:55:17
I have tried aborting the upload by closing the tab while using a simple upload controller (not Skipper) and there is no crash:
var uploadFile = req.file('fileTest');
console.log(uploadFile);
uploadFile.upload(function onUploadComplete (err, files) { // Files will be uploaded to .tmp/uploads
if (err) return res.serverError(err); // IF ERROR Return and send 500 error with error
console.log(files);
res.json({status:200,file:files});
});
So, did anybody see this happening and is there any workaround?
This issue has been solved in skipper#0.5.4 and skipper-disk#0.5.4
Ref.: https://github.com/balderdashy/skipper/issues/49
Also there is an Issue in skipper-gridfs#0.5.3
Link: https://github.com/willhuang85/skipper-gridfs/issues/20

How to check if function throw an error in DOH?

I'm trying to check if a function throws error, and made this:
define([
'doh/runner',
'app/Obj'
], function(
doh,
Obj
){
doh.register('Test Obj exception', [
function () {
try {
new Obj(); // should throw error
} catch(e) {
doh.t(e, 'should give an error if no parameters given');
}
}
]);
Obj.js file:
...
constructor: function (args){
if (!args) { throw 'Error' }
...
}
...
But maybe where is some right method for this thing in Doh ? Can someone explain? Thanks
You want doh.assertError()
Example:
doh.assertError(TypeError, this.field, "setValue",
[{
CreatedOn: "March 10th, 2014"
}],
"setValue() on an invalid format should throw a TypeError");
This example test shows that DOH catches and displays an error correctly.
This gist is the test, and contains this code:
var Obj = function () {
if (arguments.length < 1) {
throw 'Error - There are ' + arguments.length + ' arguments';
}
};
define(["doh/runner"], function(doh){
var tests = [
function () {
new Obj(); // wrong call
}
];
doh.register('Test Obj exception', tests);
});
The screenshot shows the 1 error, and the error msg from the Error thrown: