$ is not defined in mocha chai test script - javascript

i am trying to write a unit test case for a js function, its inside a .js file am loading that to a test.js file and then run
npm test test.js
my test script contains
const app = require('../js/customJs/myjs.js');
var assert = require('chai').assert;
const jsdom = require("jsdom");
const { JSDOM } = jsdom;
describe('Testing my test functions', function () {
console.log("ready 2 test d dom");
const dom = new JSDOM('<!DOCTYPE html><p id="myid"></div>');
it('check the return value of helloworld module', function () {
assert.equal(dashboard_tab.helloworld(),"hello");
});
});
'myjs.js' file has helloworld function which gets a value from a dom element and call an ajax call ,
so i am trying to unit test if the return value is "hello"('of course this test fails, since that function will not be returning hello'),but while running this test script i was getting error like '$ is not defined'
myjs.js
var count = 0;
function helloworld(){
var id_Val = $("#myid").val(); //i was getting $ is not defined here when i run test.js
$.ajax({
url: "test/",
data: { 'id': id_Val },
dataType: 'json',
success: function (data) {
//some code
}
});
}
i tried
global.$ = require('jquery')(window); // now, window is not defined
how to unit test a js function which includes jquery ($)

This might be caused by $ conflict
Please click here to know how to avoid it.
$conflict also occurs when you load jQuery file multiple times. Could you please check that also

Related

How to modify test results' output in mocha.js (or another library)

I am creating a test suite that will be run by mocha. In the test, I plan on using should and chai at the very least. I am testing JSON objects. I want mocha to be silent about successful tests and I want to control what the errors look like at the end of the run. Right now, there is a lot of red text describing the JSON object and other information. What I want is to override the output.
Here is an example test for an element in the JSON object which I would import from testData.
var should = require("should");
var chai = require("chai");
var expect = chai.expect;
const testData = require("./testData");
for (t of testData.data) {
describe("This will fail", function() {
it("Should have a zipperNut",function(done) {
t.should.have.property('zipperNut');
done();
});
});
}
What I want is to see just this:
$ mocha testSuite.js
zipperNut
$
And so on for all the tests I want to run. Can I do this? Do I need to use a different library?
Mocha's output is determined by something called a "default reporter". If you want to change the output you can specify a different reporter, which is presumably available through npm or similar. To specify a new custom reporter you do this:
$ mocha --reporter my-reporter.js
Where my-reporter.js is the file containing my "reporter". For me, I just want the plain name of the failing tests, so my reporter would look like:
'use strict';
const Mocha = require('mocha');
const {
EVENT_RUN_END,
EVENT_TEST_FAIL,
} = Mocha.Runner.constants;
class MyReporter {
constructor(runner) {
const stats = runner.stats;
runner
.on(EVENT_TEST_FAIL, (test, err) => {
console.log(
`${test.title}`
);
})
.once(EVENT_RUN_END, () => {
console.log(`end: ${stats.passes}/${stats.passes + stats.failures} ok`);
});
}
}
module.exports = MyReporter;
Documentation here:
https://mochajs.org/api/tutorial-custom-reporter.html

truffle test will only run one contract

I have an instability issue.
I'm using openzeppelin-test-helpers, and first had an issue with typescript saying Could not find a declaration file for module '#openzeppelin/test-helpers'.. This issue was solved by creating a .d.ts file containing declare module "#openzeppelin/test-helpers";.
However, adding this created a new problem, which is that now, most of the time, only one file is being run by rm -rf build && truffle test (I guess this is similar to truffle test --reset).
I got 2 test files. The first one looks like:
require("chai")
.use(require("chai-as-promised"))
.should();
const EventHandler = artifacts.require("EventHandler");
const { expectRevert } = require("#openzeppelin/test-helpers");
contract("EventHandler", function([_, superAdmin0, admin0, device0]) {
beforeEach(async function() {
this.eventHandler = await EventHandler.new(superAdmin0);
});
describe("Initial tests", function() {
it("should print hello", async function() {
await this.eventHandler
.printHello()
.should.eventually.equal("Hello");
});
});
});
The second one looks like:
require("chai")
.use(require("chai-as-promised"))
.should();
const { expectRevert } = require("#openzeppelin/test-helpers");
const EventHandler = artifacts.require("EventHandler");
contract("Roles", function([_, superAdmin0, superAdmin1, admin0, device0]) {
beforeEach(async function() {
this.EventHandler = await EventHandler.new(superAdmin0);
});
it("...should work", async function() {});
});
When I comment the content of one file, or just what's inside contract(..., {}), the other file works just fine and the tests pass successfully.
However, whenever I leave those 2 files uncommented, I get a massive error:
Error: Returned values aren't valid, did it run Out of Gas?
Of course, resetting ganache-cli didn't solve anything...
Does anyone know where it could come from?

CasperJS via CLI: How to load external JS files?

This might be a stupid question (CasperJS noob): given this example from the CasperJS docs:
// cow-test.js
casper.test.begin('Cow can moo', 2, function suite(test) {
var cow = new Cow();
test.assertEquals(cow.moo(), 'moo!');
test.assert(cow.mowed);
test.done();
});
If Cow() is defined in a file \path\to\myCowClass.js, how do I load this class when I am using CasperJS via CLI? Is this a job for the files config param or for clientScripts?
I would really love if anybody had a concise tutorial/example.
Let's take your Cow.js file. I assume it looks like this:
function Cow() {
this.mooed = false;
}
Cow.prototype.moo = function () {
this.mooed = true;
return 'moo!';
}
This file should be a dependency of your test. Here you can:
Inject your "class" file from the command line using the includes option
Inject your "class" file from your test file using phantom.injectJs
With --includes
casperjs test --includes=/path/to/Cow.js cow-test.js
With phantom.injectJs
// cow-test.js
phantom.injectJs('/path/to/Cow.js');
casper.test.begin('Cow can moo', 2, function suite(test) {
var cow = new Cow();
test.assertEquals(cow.moo(), 'moo!');
test.assert(cow.mooed);
test.done();
});

Mocking console.log()/Any Other Function in MOCHA testing framework

I am writing test cases for NODE JS API. But wherever console.log() is there in routes or services of NODE JS File, it gets printed to CLI. Is there a way to mock these so that these won't get printed in CLI.
I have explored couple of libraries like Sinon, Stub for mocking. But couldn't grasp the working of those libraries.
You can override function entirely: console.log = function () {}.
You should not try to mock console.log itself, a better approach is for your node modules to take a logging object. This allows you to provide an alternative (ie. a mock) during testing. For example:
<my_logger.js>
module.exports = {
err: function(message) {
console.log(message);
}
}
<my_module.js>
var DefaultLogger = require('my_logger.js');
module.exports = function(logger) {
this.log = logger || DefaultLogger;
// Other setup goes here
};
module.exports.prototype.myMethod = function() {
this.log.err('Error message.');
};
<my_module_test.js>
var MyModule = require('my_module.js');
describe('Test Example', function() {
var log_mock = { err: function(msg) {} };
it('Should not output anything.', function() {
var obj = new MyModule(log_mock);
obj.myMethod();
});
});
The code here I've simplified, as the actual test isn't the reason for the example. Merely the insertion of alternative logging.
If you have a large codebase with lots of console.log calls, it is better to simply update the code as you add tests for each method. Making your logging pluggable in this way makes your code easier and more receptive to testing. Also, there are many logging frameworks available for node. console.log is fine during development when you just want to dump out something to see what's going on. But, if possible, try to avoid using it as your logging solution.
I could not find a solution which only hides the console.log calls in the module to be tested, and mocks none of the calls of the testing framework (mocha/chai in my case).
I came up with using a copy of console in the app code:
/* console.js */
module.exports = console;
/* app.js */
const console = require('./console');
console.log("I'm hidden in the tests");
/* app.spec.js */
const mockery = require('mockery');
var app;
before(() => {
// Mock console
var consoleMock = {
log: () => {}
}
mockery.registerMock('./console', consoleMock);
// Require test module after mocking
app = require('./app');
});
after(() => {
mockery.deregisterAll();
mockery.disable();
});
it('works', () => {});
You could do something along the lines of adding these before/after blocks to your tests, but the issue is that mocha actually uses console.log to print the pretty messages about the results of the test, so you would lose those
describe('Test Name', function() {
var originalLog;
beforeEach(function() {
originalLog = console.log;
console.log = function () {};
});
// test code here
afterEach(function() {
console.log = originalLog;
})
})
The problem is that your output would just look like
Test Name
X passing (Yms)
Without any intermediate text

How to use jsdom.jQueryify with jasmine-node?

Is it possible to user jasmine-node with the jQueryify feature of jsdom? What I'm trying to do is use NodeJS to test some JavaScript that depends on the presence of the DOM.
Here is a reduced case of what I tried. When I run the script, jasmine-node recognizes the spec, but doesn't run the expect():
var fs = require('fs'),
jsdom = require('jsdom'),
window = jsdom.createWindow(),
jasmine = require('jasmine-node')
describe("jQueryify", function() {
it('should run the test!', function () {
jsdom.jQueryify(window, function (window, jquery) {
expect(1).toEqual(1)
})
})
})
Alternately, is there a different/better way to test stuff in NodeJS that assumes a browser-like environment?
OK, based on one this answer to a semi-related question, I was able to get the expect() to execute. I guess the answer to my question is not to use the built-in jQueryify function, but to pull in jQuery 'manually'.
var fs = require('fs'),
window = require('jsdom').jsdom('<html><head></head><body></body></html>').createWindow(),
script = window.document.createElement('script'),
jasmine = require('jasmine-node')
describe("jQueryify", function() {
it('should run the test!', function () {
script.src = './path/to/jquery.js'
script.onload = function () {
expect(typeof window.$).toEqual('function')
asyncSpecDone()
}
window.document.head.appendChild(script)
asyncSpecWait()
})
})

Categories