Cannot convert undefined or null to object at Function.keys - javascript

I'm using the matchFeature example from NodeJS but when i try to test the following error occurs in the
const cv = require('opencv4nodejs'); line from the example.
test/matchFeature.test.js
● Test suite failed to run
TypeError: Cannot convert undefined or null to object
at Function.keys ()
at Object. (node_modules/opencv4nodejs/lib/cv.js:63:8)
at Object.
(node_modules/opencv4nodejs/lib/opencv4nodejs.js:11:79)
I think is a problem when loading the module, but i cant fix it.
I'm using Jest for testing.
If i run the file with NodeJS, works without problems:
https://prnt.sc/sq41s9
And if i run test with jest, gives the error above:
https://prnt.sc/sq42mb
The images are from the file cv.js running the file and the test
EDIT: Screenshot from jest index.js (Module null)
https://prnt.sc/sq5rxl

I was able to solve it with a global setup script which loads the module.
// setup.js
module.exports = async () => {
const cv = require('opencv4nodejs');
console.log('cv.version', cv.version);
};
And in the jest Config in package.json:
"jest": {
...
"testEnvironment": "node",
"globalSetup": "./setup.js"
}

Related

ReferenceError: TextEncoder is not defined when importing jsdom library

I have these two files:
test.js:
const jsdom = require("jsdom");
const hello = () => {
console.log("hello!");
};
module.exports = {
hello
};
and
server.js:
const hello = require('./stuff/test');
hello.hello();
directory structure:
myprojectfolder
backend
src
stuff
test.js
server.js
When I run server.js I get the ReferenceError: TextEncoder is not defined error:
/home/myusername/projects/myprojectfolder/node_modules/whatwg-url/lib/encoding.js:2
const utf8Encoder = new TextEncoder();
^
ReferenceError: TextEncoder is not defined
If I remove const jsdom = require("jsdom"); line from test.js, server.js runs fine and without any errors (outputs hello).
Why does it happen and how do I fix it (while still being able to import and use jsdom inside test.js?).
Well, it took me all day, but finally I managed to pull it together.
My problem was that tests didn't run because of that error.
So, in package.json under "scripts" I added the following:
"test": "jest --verbose --runInBand --detectOpenHandles --forceExit"
And in jest.config.js, I added the following:
globals: {
"ts-jest": {
tsConfigFile: "tsconfig.json"
},
TextEncoder: require("util").TextEncoder,
TextDecoder: require("util").TextDecoder
}

Jest TypeError: Document.save is not a function

I'm trying to write some tests for an Express app where I have an User model. One of my methods looks like this:
let user = await User.findById(req.params.userId);
user.name = req.body.name || user.name;
user.password = req.body.password || user.
user = await user.save();
The code runs as it should, but when I test it, Jest complains:
TypeError: user.save is not a function
Right now I'm mocking my whole User model like this:
jest.mock('../../models/User');
I tried to mock the save function like this, but nothing changed:
jest.spyOn(User.prototype, 'save')
.mockImplementationOnce(() => Promise.reject('fail update'))
As I said before, the code runs fine. I don't get this error when I run the server.
However, there is one weird thing happening: when I run the tests I get this warning from mongoose
Mongoose: looks like you're trying to test a Mongoose app with Jest's default jsdom test environment. Please make sure you read Mongoose's docs on configuring Jest to test Node.js apps: http://mongoosejs.com/docs/jest.html
I read the docs and what it said was to set testEnvironment as 'node' on Jest config file, which I'm already doing. This is my jest.config.js file:
module.exports = {
testEnvironment: 'node'
};
However I keep getting the warning.
This is my test script:
jest --watchAll
Any help will be appreaciated. Thanks in advance
The reason why you are receiving that error is this line:
let user = User.findById(req.params.userId)
findById() is an asynchronous method, so you have to put the await keyword in the code, like this:
let user = await User.findById(req.params.userId)
As your code is not really awaiting a response from findById() that user variable is undefined hence user.save() indeed is not a function. You could try to print console.log(user), and it'll be undefined.
To avoid this message "Mongoose: looks like you're trying to test a Mongoose app with Jest's..." you have to configure Jest in your package.json, like this:
"jest": {
"testEnvironment": "node"
},

WebdriverIO Custom Reporter - TypeError: Cannot read property 'write'/'complete' of undefined

I am implementing a custom reporter in WebdriverIO. Following a tutorial (https://webdriver.io/docs/customreporter.html), I have written the following code:
let Reporter = require ('#wdio/reporter').default;
Reporter.reporterName = 'HTMLReporter';
module.exports = class HTMLReporter extends Reporter {
constructor (options) {
options = Object.assign(options, { stdout: true });
super(options);
}
onTestPass (test) {
this.write(`Congratulations! Your test "${test.title}" passed!`);
}
};
When running this code, however, I get the error TypeError: Cannot read property 'write' of undefined. There seems to be an issue with write command in the line this.write('Congratulations! Your test "${test.title}" passed!');.
I am able to bypass this error by changing this.write('Congratulations! Your test "${test.title}" passed!'); to console.log('Congratulations! Your test "${test.title}" passed!');, however when I run this code, I get the error TypeError: Cannot read property 'complete' of undefined. Why am I getting these errors? How can I fix my code to make it run correctly?
since i am facing the same problem, I have decided to replace:
this.write();
with:
fs.writeFileSync();
and it worked as expected

Error: Cannot find module 'utils'

I'm running a file main.js using Casper.js via casperjs main.js, which uses a module ./lib/myUtils.js, which in turn uses
var utils = require('utils')
But running casperjs main.js throws the error
Error: Cannot find module 'utils'
phantomjs://bootstrap.js:289
phantomjs://bootstrap.js:254 in require
/Users/username/casper-test/lib/myUtils.js:2
/Users/username/casper-test/lib/myUtils.js:63
TypeError: 'undefined' is not a function (evaluating 'myUtils.loadCookies()')
/Users/username/casper-test/main.js:104
The functions being imported have "use strict"; in their first line.
However putting the code from myUtils.js directly into main.js avoids the error. Why is this?
I suppose you need to insert var require = patchRequire(require); at the beginning of your file ( myUtils.js ).

Uncaught exception with qunit and jquery

I'm facing an issue while trying to get javascript unit tests to work at the command line using qunit.
Here's some sample code to reproduce the error:
file util.js:
function abc() {
return 'abc';
}
if (typeof module !== 'undefined' && module.exports) {
module.exports = {
abc: abc
};
}
file util-tests.js
var qunit = require("qunit");
test("Test abc function", function () {
equal(util.abc(), 'abc');
});
With these files, I can run tests using the following command (gives a table-like output in the shell with the test results):
qunit -c util:util.js -t util-tests.js
Now it breaks if I add the following to util.js
$(document).ready(function () {
/* some code here */
});
Here's the error output:
qunit -c util:util.js -t util-tests.js
Testing /home/mfrere/jstst/util.js ... [Error: Uncaught exception in child process.]
same problem with:
var a = $;
or:
var a = document;
So this makes me think that I need to import jQuery somehow, so I thought about adding jquery.js as a dependency to the command, like this:
qunit -c util:util.js -t util-tests.js -d jquery.js
The above command gives me the same 'Uncaught exception' error, even if util.js doesn't contain any reference to '$'.
I'll probably need to do something else to get qunit to recognize 'document' as well, but I don't know what or how.
Now here's my question: what should I do to get this to work? It is important to keep in mind I want to test my files at the command line, not in a browser.
Just in case I did something wrong in the setup process, this is how I installed node/qunit (under ubuntu):
git clone git://github.com/creationix/nvm.git ~/.nvm
in .bashrc, I added the following line:
source ~/.nvm/nvm.sh
picked a specific version of node
nvm install v0.9.2
nvm alias default 0.9
and installed qunit
npm install -g qunit
finally I had to add this in .bashrc as well:
export NODE_PATH=~/.nvm/v0.9.2/lib/node_modules
You haven't imported jQuery:
$ = require('jquery'),
jQuery = require('jquery');
If you're using browserify, change that to 'jquery-browserify'.

Categories