Frisby.js: Expected valid JavaScript object to be given, got undefined - javascript

I'm having some trouble getting a new test off the ground with this Frisby.js API testing framework.
For context, I have written some other tests that don't require reading in reference files from disk, and have run some of the samples that came with Frisby, and they all run very quickly and accurately. Really liking the speed of execution so far. Seeing as how all of that comes back OK, I am fairly certain that my environment is sound.
Below is a simplified version of a problematic JavaScript file, that I am running through jasmine-node:
var frisby = require('frisby');
var fs = require('fs');
var path = require('path');
var URL = 'http://server/api/';
var getJSON = fs.readFileSync(path.resolve(__dirname, 'GET.json'), 'utf-8').replace(/^\uFEFF/, ''); // the .replace removes the BOM from the start of the file
console.log(getJSON); // this dumps the file contents to the screen, no problems here
frisby.create('GET from API')
.get(URL + 'Endpoint?Parameters=Values')
.expectStatus(200) // tests that HTTP Status code equals expected 200, still no worries
.expectJSON(getJSON) // this is where the 'undefined' error is thrown
.toss();
Running the test from the command line is very straight forward:
C:\Testing\Frisby> jasmine-node apitest.js
I believe I'm doing things in the right order, with the synchronous file read, and then the Frisby calls afterwards, but when executed it throws the following error:
Failures:
1) Frisby Test: GET from API
[ GET http://server/api/Endpoint?Parameters=Values ]
Message:
TypeError: Expected valid JavaScript object to be given, got undefined
Stacktrace:
TypeError: Expected valid JavaScript object to be given, got undefined
at _jsonContains (C:\Users\jlucktay\AppData\Roaming\npm\node_modules\frisby\lib\frisby.js:1182:11)
at jasmine.Matchers.toContainJson (C:\Users\jlucktay\AppData\Roaming\npm\node_modules\frisby\lib\frisby.js:1141:12)
at null.<anonymous> (C:\Users\jlucktay\AppData\Roaming\npm\node_modules\frisby\lib\frisby.js:686:24)
at null.<anonymous> (C:\Users\jlucktay\AppData\Roaming\npm\node_modules\frisby\lib\frisby.js:1043:43)
at Timer.listOnTimeout [as ontimeout] (timers.js:110:15)
Finished in 0.292 seconds
1 test, 2 assertions, 1 failure, 0 skipped
I have the jasmine-node and frisby packages both installed globally via npm, and have used npm link frisby which created the appropriate junction from my testing directory over to %APPDATA%\npm.
I have also tried changing the code around, to use fs.readFile instead of fs.readFileSync with the frisby calls inside the callback, but still have the same problem.
As I said above, my other tests and the samples that came with Frisby run and come back without error. Specifically, the httpbin_binary_post_put_spec.js sample uses almost identical code to what I ended up writing myself, and that sample works just fine.
I have routed the HTTP requests through Fiddler and can see the request and response, and everything looks fine there. It gets a HTTP 200 and the response body has the expected JSON that I want to compare against the file contents.
Why am I getting this error about an undefined object?

Rubber duck problem solving seems to have rescued me from my own stupidity.
The string needed to be turned into a proper JSON object:
.expectJSON(getJSON) -> .expectJSON(JSON.parse(getJSON))

Related

How to get SubtleCrypto work with testcafe?

I am generating SHA256 using SubtleCrypt Web API on client-side as following:
const hashBuffer = await crypto.subtle.digest('SHA-256', msgBuffer);
Everything works fine except for when I execute tests via testcafe. The captured console error says TypeError: Cannot read properties of undefined (reading 'digest') meaning crypto.subtle is undefined.
I know that SubtleCrypto is available only in secure contexts which also includes localhost and I am using localhost to run my end-to-end testcafe tests.
What am I doing wrong?
You need to run TestCafe over HTTPS protocol. See more information in the following help topic: test-https-websites.

TypeError when testing with Jest and Formidable

I have wrote a cusom express middleware to pars an incoming multipart form.
The middleware works fine when launched in local or deployed but the test with jest fails with the error
TypeError: Cannot set property domain of [object process] which has only a getter
The issues seems to come from the package asap used by formidable.
I think that Jest is putting some limitations on the process object since the line where everything breaks is
domain.active = process.domain = null;
in the file raw.js
Does anyone has any workaround or solution for this issue? I cannot migrate to formidable V3 at the moment so that's not an option

Using axios-cookiejar-support with Vue.js on the backend

Has anyone used axios-cookiejar-support with Vue.js on the backend?
I'm getting the following error in the Chrome debugger:
Uncaught (in promise) TypeError: axiosCookieJarSupport is not a function
And when I console.log(axiosCookieJarSupport) I see "undefined" when I run the the init code shown on the axios-cookiejar-support site that modifies Axios to support cookies:
const axiosCookieJarSupport = require('axios-cookiejar-support').default;
axiosCookieJarSupport(axios); // <--- error occurs here
Obviously, I tried it with a Node.js console application and it works, and I can console.log axiosCookieJarSupport and I see that it is a function in the console application.
I'm guessing I need to somehow tell Webpack (which I believe Vue.js uses) to preload axios-cookiejar-support, as opposed to just include it in the package.json (which I did), but I'm not sure how to do it.

Available modules in node script

why do I get different results when trying to find out more about the http module in node.js in the following to ways?
If I enter the node REPL and then print the content of the http module, i.e. if I run
me#mymachine:~> node
> console.log(http)
I get all the details of the http object:
{ IncomingMessage:
{ [Function: IncomingMessage]
super_:
{
...
If I write a script file called, say, script.js containing the following single line
console.log(http);
and execute it by running
node script.js
I get
ReferenceError: http is not defined
I would have expected both cases to behave in the same way - either the http module is preloaded or not. Why is there a difference? What am I getting wrong here?
I thought I could 'fix' this by preloading module http by running (in version 2)
node -r http script.js
Shouldn't this preload module http and thus avoid the reference error?
Looking forward to your input!
Repl has all the standard Node.js core modules required by default.
https://nodejs.org/api/repl.html#repl_accessing_core_node_js_modules

debug V8 with node-inspector

I'm trying to debug my JavaScript scripts, which are running in V8, with node-inspector. On the app side, I just did
v8::Debug::EnableAgent("MyApp", 5858);
Node-inspector connects fine and even is able to pause/unpause and to show the code. However, step-wise execution does not work, neither breakpoints and probably a lot of other things. When I try to do such things, I get these errors from Node-inspector:
Node Inspector v0.7.0
Visit http://127.0.0.1:8080/debug?port=5858 to start debugging.
Received request for a method not implemented: Debugger.setSkipAllPauses
Received request for a method not implemented: Debugger.setSkipAllPauses
Received request for a method not implemented: Debugger.setSkipAllPauses
Received request for a method not implemented: Debugger.setBreakpoint
Received request for a method not implemented: Debugger.setBreakpoint
Received request for a method not implemented: Debugger.setBreakpoint
So I guess I'm missing something.
I'm not sure if what I'm trying to do is even supported - because I guess, node-inspector is meant for Node.js and not for arbitrary V8, right? If so, what would be needed to make it work?
Thanks for the help by Miroslav, esp. to run DEBUG=node-inspector:protocol:* node-inspector, I got a bit further. Step-wise execution works now, and breakpoints do to in most cases (except when you select the wrong Source file - see below).
I provided a global process object like this:
// process object: http://nodejs.org/api/process.html#process_process
process.stdout = ...
process.stderr = ...
process._baseDir = ...
process.mainModule = {filename: process._baseDir + "/main.js"}
process.argv = ["myapp.exe", process.mainModule.filename]
process.cwd = function() { return process._baseDir; }
Now I get the error Internal error: TypeError: Cannot read property 'line' of null in the console. In node-inspector, I get this:
Wed, 19 Mar 2014 11:58:43 GMT node-inspector:protocol:v8-debug request: {"seq":170,"type":"request","command":"backtrace","arguments":{"inlineRefs":true,"fromFrame":0,"toFrame":50,"maxStringLength":10000}}
Wed, 19 Mar 2014 11:58:43 GMT node-inspector:protocol:devtools frontend: {"method":"Debugger.setOverlayMessage","id":48}
Wed, 19 Mar 2014 11:58:43 GMT node-inspector:protocol:devtools backend: {"id":48}
Wed, 19 Mar 2014 11:58:43 GMT node-inspector:protocol:v8-debug response: {"seq":41,"request_seq":170,"type":"response","success":false,"message":"Internal error: TypeError: Cannot read property 'line' of null"}
Another thing is that the script files are not always correct. On the C++ side, I'm loading them now like this:
ReturnType execJsFile(const std::string& jsSourceDir, const std::string& extfilename) {
v8::TryCatch try_catch;
std::string fullfilename = jsSourceDir + "/" + extfilename;
std::string sourceStr;
CHECK_RETURN(readFile(fullfilename, sourceStr));
// The origin is for the debugger, e.g. node-inspector. It expects an URL.
Local<String> origin = jsStr("file:///" + fullfilename);
Local<String> source = jsStr(sourceStr);
Local<v8::Script> script = Script::Compile(source, origin);
if(script.IsEmpty()) {
assert(try_catch.HasCaught());
return "JS compile failed: " + jsReportExceptionToString(Isolate::GetCurrent(), &try_catch);;
}
Local<Value> result = script->Run();
if(result.IsEmpty()) {
assert(try_catch.HasCaught());
return "JS script execution failed: " + jsReportExceptionToString(Isolate::GetCurrent(), &try_catch);
}
return true;
}
That puts all files under the file:// domain in the Sources list. However, main.js gets an extra entry under (no domain). When I make the change
process.mainModule = {filename: "file:///" + process._baseDir + "/main.js"}
it goes away, however, that is not how I would have expected ìt to be according to the doc.
When I pause/break the execution in main.js, it shows up in yet another Source [VM] main.js and gets a yellow-ish background.
Also, all files in Sources under file:// get the (function (exports, require, module, __filename, __dirname) { prefix added in the first line of the source. That line does not come from my code but from node-inspector. Why does it add that here? It is esp. strange because my code adds a slightly different prefix ( function(module, exports) {.
Run DEBUG=node-inspector:protocol:* node-inspector and inspect the messages, you might be able to find more information there. You can also try to use an older version, e.g. 0.1.9, it may have less dependencies on Node-specific stuff.
I'd say 95% of Node Inspector code uses V8 protocol only. Look for usages of DebuggerClient.prototype.evaluateGlobal to find where Node-specific functionality is used.
The first thing to change is getResourceTree in lib/PageAgent.js. Either implement your own way of listing all source files (including those not loaded yet), or return an empty tree.
UPDATE
Try Node's CLI debugger first:
$ node debug localhost:5858
To my best knowledge, the CLI debugger uses only the V8 debugger protocol features, nothing Node specific. When you are able to debug your V8 app using the CLI, you will know that any other problems are in Node Inspector and not in your V8 app.
Here is a solution for debugging V8 with node-inspector:
First of all, the latest version (0.12.3) has many extensions for debugging node.js scripts so I used an older version (0.5.0) which has less liability to node.js.
I used the following command to install v0.5.0 in Node.js command prompt:
npm install node-inspector#0.5.0
It is installed in folder "%USERPROFILE%\node_modules" by default.
I added one line of code to %USERPROFILE%\node_modules\node-inspector\lib\PageAgent.js:
getResourceTree: function(params, done) {
return; //return empty tree
...
This completes the installation.
Here is the guide to debug a javascript file executed by using the ClearScript .NET library:
Open a command prompt and execute the following command:
%USERPROFILE%\node_modules\.bin\node-inspector.cmd
You should see the following lines if node-inspector is running successfully.
Node Inspector v0.5.0
info - socket.io started
Visit http://127.0.0.1:8080/debug?port=5858 to start debugging.
Initialize your V8 engine as in the following code line (VB.NET code):
Dim engine As New V8ScriptEngine("global", V8ScriptEngineFlags.EnableDebugging, 9222)
Put a breakpoint right after this line in your code and run your application to reach this breakpoint.
Make sure you have "debugger;" statement in the first line of your JavaScript code.
Open a Chrome browser and navigate to the following address:
http://127.0.0.1:8080/debug?port=9222
Press "Continue Debugging" button in Vİsual Studio toolbar.
Now you should see your script code stopped at the first "debugger;" line in Chrome browser.
You can continue debugging from here.

Categories