Mocha, "require is not defined" when test in browser - javascript

I'm using Mocha 5.2.0, npm 6.1.0, and I'm trying to test in Chrome browser.
But When I run the test, the browser says "require is not defined".
I want to see the test result in browser, but it works in terminal.
I'm not using build system like webpack etc.
test/test.js
var assert = require("assert");
describe("Array", function() {
describe("#indexOf()", function() {
it("should return -1 when the value is not present", function() {
assert.equal([1,2,3].indexOf(4), -1);
});
});
});
index.html
...
<link href="https://cdnjs.cloudflare.com/ajax/libs/mocha/5.2.0/mocha.min.css" rel="stylesheet">
...
<body>
<div id="mocha"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/mocha/5.2.0/mocha.min.js"></script>
<script>
mocha.setup("bdd");
</script>
<script src="test/test.js"></script>
<script>
mocha.checkLeaks();
mocha.run();
</script>
</body>
package.json
{
"scripts": {
"test": "mocha"
}
}
Edited Karthikeyan
index.html
<script data-main="test/test.js" src="require.js"></script>
require.js:168 Uncaught Error: Module name "assert" has not been loaded yet for context: _. Use require([])

Require.js is missing . Import require.js inside your body before importing mocha.js

Related

Calling javascript code with 'require' from flutter web

So I saw this tutorial about calling javascript functions from flutter web: https://fireship.io/snippets/using-js-with-flutter-web/ but I ran into a problem trying to use 'require'. I have 3 files:
main.dart:
import 'dart:js' as js;
void main() async {
js.context.callMethod('demo', []);
}
test.js:
exports.testFunction = function() {
console.log("test");
}
demo.js:
test = require("./test");
function demo() {
console.log("called");
test.testFunction();
}
and my index.html file incudes the lines:
<head>
<script src="test.js" defer></script>
<script src="demo.js" defer></script>
(...)
When I run my code it prints 'called' but then it crashes and throws: 'ReferenceError: test is not defined'.
I'd like to know how to use require so I can use multiple js files and node packages

Datatable in laravel mix

I have some problem, and I was search for solving this problem, but I still didn't get the solving, I hope Anyone can help me to solve this problem, I put my code in below, Thanks :
webpack.mix.js :
mix.autoload({
jquery: ['$', 'jQuery', 'window.jQuery'],
})
mix.scripts([
.js('resources/js/app.js', 'public/js').version()
.js('resources/js/bootstrap.js', 'public/js').version()
.js('resources/js/occupant.js', 'public/js').version()
.sass('resources/sass/app.scss', 'public/css').version()
]);
bootstrap.js :
try {
window.Popper = require('popper.js').default;
window.$ = window.jQuery = require('jquery');
require('bootstrap');
require('../../node_modules/datatables.net/js/jquery.dataTables.js');
require('../../node_modules/datatables.net-bs4/js/dataTables.bootstrap4.js');
} catch (e) {}
occupant.js :
var $ = require('jquery');
$(document).ready(function () {
$("#tblOccupant").DataTable(function () {
});
});
my console error :
occupant.js?id=043c6fbba06b4c7cd537:10984 Uncaught TypeError: $(...).DataTable is not a function
Your app is not able to locate datatables try following way to get it work
Instal depedencies via npm
npm install datatables.net-bs4
then
npm install datatables.net-buttons-bs4
add them to resources/js/bootstrap.js like
require('datatables.net-bs4');
require('datatables.net-buttons-bs4');
Edit resources/scss/app.scss and add the following:
// DataTables
#import "~datatables.net-bs4/css/dataTables.bootstrap4.css";
#import "~datatables.net-buttons-bs4/css/buttons.bootstrap4.css";
Make sure your webpack.mix.js contains
mix.js('resources/js/app.js', 'public/js')
.sass('resources/sass/app.scss', 'public/css');
and you have added
<link href="{{asset(mix('css/app.css'))}}" rel="stylesheet">
in the head of html and
<script src="{{asset(mix('js/app.js'))}}"></script>
just before closing </body> tag
then run npm run watch or npm run dev

ACE editor installed with bower does not find my mode

I wrote a custom mode for the ACE editor
my-mode.js
ace.define('my-mode', [/* ... */], function(require, exports, module) { /* ... */ });
that I try to use
index.js
var editor = ace.edit('editor');
editor.getSession().setMode('my-mode');
I installed the ACE editor (ace-builds) and requirejs with bower
bower.json
{
"name": "my-project",
"dependencies": {
"ace-builds": "^1.2.3",
"requirejs": "^2.2.0"
}
}
and configured requirejs
requirejs-config.js
require.config({
paths: {
ace: "bower_components/ace-builds/src-noconflict/ace"
}
});
My page looks like this
index.html
<body>
<div id="editor"></div>
<script src="bower_components/requirejs/require.js"></script>
<script src="requirejs-config.js"></script>
<script src="bower_components/ace-builds/src-noconflict/ace.js"></script>
<script src="my-mode.js"></script>
<script src="index.js"></script>
</body>
Sadly, the call
editor.getSession().setMode('my-mode');
leads to an error
Failed to load resource: http://localhost:5555/bower_components/ace-builds/src-noconflict/mode-my-mode.js
the server responded with a status of 404 (Not Found)
How can I configure ace and requirejs such that my-mode is found?
I found a solution. Before my-mode is used (for example at the beginning of index.js) call
ace.config.setModuleUrl('my-mode', '/path/to/my-mode.js');

Require fails on a PhantomJs test

I have a simple library,
-- src/lib.js --
function libtest() {
return 2;
}
that I want to test, which I gather will need PhantomJs. I have a test file:
-- test/lib.test.js --
var fs = require('fs');
var assert = require('assert');
describe('Test module', function() {
var s = fs.readFileSync('../src/lib.js', 'utf8');
eval(s);
it('Shows name', function() {
assert.equal(libtest(), 2);
});
});
which I make ready for the browser:
# browserify lib.test.js -o tests.js
and then include in my main page:
-- test/index.html --
<html>
<head>
<meta charset="utf-8">
<title>Mocha Tests</title>
<link href="../../node_modules/mocha/mocha.css" rel="stylesheet" />
</head>
<body>
<div id="mocha"></div>
<script src="../../node_modules/mocha//mocha.js"></script>
<script>mocha.setup('bdd')</script>
<script src="tests.js"></script>
<script>
if (window.mochaPhantomJS) mochaPhantomJS.run();
else mocha.run();
</script>
</body>
</html>
however, when I run the tests:
# grunt test
I get the following error:
Running "mocha_phantomjs:all" (mocha_phantomjs) task TypeError:
'undefined' is not a function (evaluating
'fs.readFileSync('../src/lib.js', 'utf8')')
at file:///Users/ekkis/Development/tst/test/tests.js:5
at
file:///Users/ekkis/Development/tst/node_modules/mocha//mocha.js:529
at file:///Users/ekkis/Development/tst/test/browser/tests.js:10 in
s at file:///Users/ekkis/Development/tst/test/browser/tests.js:1 in
e at file:///Users/ekkis/Development/tst/test/browser/tests.js:1 at
file:///Users/ekkis/Development/tst/test/browser/tests.js:1090 Unsafe
JavaScript attempt to access frame with URL about:blank from frame
with URL
file:///Users/ekkis/Development/tst/node_modules/mocha-phantomjs-core/mocha-phantomjs-core.js.
Domains, protocols and ports must match.
which seems to be complaining about the fs being undefined. however, if the require('assert') worked, I would imagine the require('fs') should work. but I don't quite know the context in which this is run.
what am I missing?
ok. the answer is simply to include the library in the .html. since the tests run within the browser then the library will be available. like this:
<body>
<div id="mocha"></div>
<script src="../../node_modules/mocha//mocha.js"></script>
<script>mocha.setup('bdd')</script>
<script src="../../src/lib.js"></script>
<script src="tests.js"></script>

JS: use grunt + mocha + phantomjs

I used the yeoman webapp-generator to create a fancy website template. It creates a test-folder and scaffolds the whole project incl. one simple unittest. To try the phantomjs functionality I added an additional function:
describe("DOM Test", function () {
var el = document.createElement("div");
el.id = "myDiv";
el.innerHTML = "Hello World!";
document.body.appendChild(el);
var myEl = document.getElementById('myDiv');
it("has the right text", function () {
(myEl.innerHTML).should.equal("Hello World!");
});
});
But when I run grunt test I always get this annoying error:
Running "mocha:test" (mocha) task
Testing: test/index.html
Warning: PhantomJS timed out, possibly due to a missing Mocha run() call. Use --force to continue.
Aborted due to warnings.
My mocha-entry within the Gruntfile looks like this (its a slightly modified version of the generated one. I replaced the url by a relative path with wildcard):
mocha: {
test: {
src: ['test/**/*.html'],
}
},
And the test/index.html looks like this:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Mocha Spec Runner</title>
<link rel="stylesheet" href="bower_components/mocha/mocha.css">
</head>
<body>
<div id="mocha"></div>
<script src="bower_components/mocha/mocha.js"></script>
<script>mocha.setup('bdd')</script>
<script src="bower_components/chai/chai.js"></script>
<script>
var assert = chai.assert;
var expect = chai.expect;
var should = chai.should();
</script>
<!-- include source files here... -->
<!-- include spec files here... -->
<script src="spec/test.js"></script>
<script>
if (window.mochaPhantomJS) { mochaPhantomJS.run(); }
else { mocha.run(); }
</script>
</body>
</html>
And I tried the following things (without success):
run bower twice (suggested by this guy)
added grunt.config.set('server.port', 7002) (suggested by this github issue post)
Go to your test folder and run bower install:
cd test
bower install
Then try again to run grunt test.
You have two bower_components folders, one in root and one in test.

Categories

Resources