
Security News
vlt Launches "reproduce": A New Tool Challenging the Limits of Package Provenance
vlt's new "reproduce" tool verifies npm packages against their source code, outperforming traditional provenance adoption in the JavaScript ecosystem.
Mocha is a feature-rich JavaScript test framework running on Node.js and in the browser, making asynchronous testing simple and fun. Mocha tests run serially, allowing for flexible and accurate reporting, while mapping uncaught exceptions to the correct test cases.
Test Organization
Organize tests in suites and sub-suites using describe() and context(), and specify test cases using it().
"use strict";\nconst assert = require('assert');\ndescribe('Array', function() {\n describe('#indexOf()', function() {\n it('should return -1 when the value is not present', function() {\n assert.equal([1, 2, 3].indexOf(4), -1);\n });\n });\n});
Asynchronous Testing
Support for testing asynchronous code with ease, using callbacks, promises, or async/await.
"use strict";\nconst assert = require('assert');\ndescribe('User', function() {\n describe('#save()', function() {\n it('should save without error', function(done) {\n const user = new User('Luna');\n user.save(function(err) {\n if (err) done(err);\n else done();\n });\n });\n });\n});
Hooks
Lifecycle hooks such as before(), after(), beforeEach(), and afterEach() for setting up preconditions and clean-up after tests.
"use strict";\ndescribe('Connection', function() {\n before(function() {\n // runs once before the first test in this block\n });\n\n after(function() {\n // runs once after the last test in this block\n });\n\n beforeEach(function() {\n // runs before each test in this block\n });\n\n afterEach(function() {\n // runs after each test in this block\n });\n\n // test cases\n});
Jest is a delightful JavaScript Testing Framework with a focus on simplicity. It works out of the box for any React project and is often compared to Mocha for its comprehensive feature set including a built-in assertion library and mock functions.
Jasmine is a behavior-driven development framework for testing JavaScript code. It does not rely on browsers, DOM, or any JavaScript framework. Thus, it's suited for websites, Node.js projects, or anywhere that JavaScript can run. It's compared to Mocha for its clean syntax and testing capabilities.
AVA is a test runner for Node.js with a concise API, detailed error output, and process isolation that lets you develop with confidence. It is often compared to Mocha for its modern, concurrent testing features, but differs in its approach to running tests in parallel by default.
Mocha is a simple, fun, extensible JavaScript test framework rich with features, running on node and the browser. Mocha tests run serially, allowing reporting flexibility, and mapping uncaught exceptions to the correct test cases; This also makes Mocha an ideal choice when mocking and stubbing is involved.
Mocha allows you to use any assertion library you want, if it throws an error, it will work. This means you can utilize libraries such as should, node's regular assert
module, or others.
Testing asynchronous code with Mocha could not be simpler, when your tests are sync simple omit the callback, when they are async add a callback and invoke it when your test is complete.
mocha-debug(1)
for node debugger supportdone()
assert
, etc)dot
: a dot matrixdoc
: a documentation generator (html) based on your testslanding
: a unicode landing strip ✈tap
: test-anything-protocol (TAP) producerprogress
: a progress barspec
: hierarchical specificationlist
: similar to spec
as a flat-listjson-stream
: streaming JSON delimited by a LFjson
: a single JSON chunk on exit
Usage: mocha [options] [files]
Options:
-h, --help output usage information
-V, --version output the version number
-r, --require <name> require the given module
-R, --reporter <name> specify the reporter to use
-u, --ui <name> specify user-interface (bdd|tdd|exports)
-g, --grep <pattern> only run tests matching <pattern>
-t, --timeout <ms> set test-case timeout in milliseconds [2000]
-s, --slow <ms> "slow" test threshold in milliseconds [75]
-G, --growl enable growl support
Reporters:
dot - dot matrix
doc - html documentation
json - single json object
progress - progress bar
list - spec-style listing
tap - test-anything-protocol
landing - unicode landing strip
json-stream - newline delimited json events
Interfaces:
bdd - describe() / it()
tdd - suite() / test()
exports - module.exports
Mocha "interfaces" providing BDD, TDD, and expresso export-style flavoured APIs on top of the internals.
describe('Array', function(){
before(function(){
// ...
});
describe('#indexOf()', function(){
it('should return -1 when not present', function(){
[1,2,3].indexOf(4).should.equal(-1);
});
it('should return the index when present', function(){
[1,2,3].indexOf(3).should.equal(2);
[1,2,3].indexOf(2).should.equal(1);
[1,2,3].indexOf(1).should.equal(0);
});
});
});
suite('Array', function(){
setup(function(){
// ...
});
suite('#indexOf()', function(){
test('should return -1 when not present', function(){
assert.equal(-1, [1,2,3].indexOf(4));
});
test('should return the index when present', function(){
assert.equal(2, [1,2,3].indexOf(3));
assert.equal(1, [1,2,3].indexOf(2));
assert.equal(0, [1,2,3].indexOf(1));
});
});
});
module.exports = {
'Array': {
'#indexOf()': {
'should return -1 when not present': function(){
[1,2,3].indexOf(4).should.equal(-1);
},
'should return the index when present': function(){
[1,2,3].indexOf(3).should.equal(2);
[1,2,3].indexOf(2).should.equal(1);
[1,2,3].indexOf(1).should.equal(0);
}
}
}
};
Mocha reporters adjust to the terminal window, and always disable ansi-escape colouring when the stdio streams are not associated with a tty.
The Dot Matrix reporter is simply a series of dots that represent test cases, failures highlight in red.
The TAP reporter emits lines for a Test-Anything-Protocol consumer.
The Landing Strip reporter is a gimmicky test reporter simulating a plane landing :) unicode ftw
The "List" reporter outputs a simple specifications list as test cases pass or fail, outputting the failure details at the bottom of the output.
The JSON reporter outputs a single large JSON object when the tests have completed (failures or not).
The JSON Stream reporter outputs newline-delimited JSON "events" as they occur, beginning with a "start" event, followed by test passes or failures, and then the final "end" event.
["start",{"total":12}]
["pass",{"title":"should return -1 when not present","fullTitle":"Array #indexOf() should return -1 when not present","duration":0}]
["pass",{"title":"should return the index when present","fullTitle":"Array #indexOf() should return the index when present","duration":0}]
["fail",{"title":"should return -1 when not present","fullTitle":"Array #indexOf() should return -1 when not present"}]
["end",{"start":"2011-08-29T03:21:02.050Z","suites":13,"passes":11,"tests":12,"failures":1,"end":"2011-08-29T03:21:02.052Z","duration":2}]
The "doc" reporter outputs a hierarchical HTML body representation of your tests, wrap it with a header, footer, some styling and you have some fantastic documentation!
For example suppose you have the following JavaScript:
describe('Array', function(){
describe('#indexOf()', function(){
it('should return -1 when the value is not present', function(){
[1,2,3].indexOf(5).should.equal(-1);
[1,2,3].indexOf(0).should.equal(-1);
})
})
})
The command mocha --reporter doc array
would yield:
<section class="suite">
<h1>Array</h1>
<dl>
<section class="suite">
<h1>#indexOf()</h1>
<dl>
<dt>should return -1 when the value is not present</dt>
<dd><pre><code>[1,2,3].indexOf(5).should.equal(-1);
[1,2,3].indexOf(0).should.equal(-1);</code></pre></dd>
</dl>
</section>
</dl>
</section>
Testing async code with mocha is simple, invoke the done()
callback
when complete, if called multiple times (due to a race-condition etc)
will cause mocha to fail, this is invaluable for testing async code.
describe('something async', function(){
it('should finish after 300ms', function(done){
setTimeout(done, 300);
})
})
The done()
callback also accepts an error, so it's easy to write
tests that adhere to node's callback convention of (err, result)
:
describe('User.save()', function(){
it('should save without failing', function(done){
var user = new User('tj');
user.save(done);
})
})
By default mocha(1)
will use the pattern ./test/*.js
, so
it's usually a good place to put your tests.
Mocha will attempt to load ./test/mocha.opts
, these are concatenated with process.argv
, though command-line args will take precedence. For example suppose you have the following mocha.opts file:
--require should
--reporter dot
--ui bdd
This will default the reporter to dot
, require the should
library,
and use bdd
as the interface. With this you may then invoke mocha(1)
with additional arguments, here enabling growl support and changing
the reporter to spec
:
$ mocha --reporter list --growl
Suites with common names are "merged" in order to produce unified reporting, especially when meta-generating tests.
describe('merge', function(){
describe('stuff', function(){
describe('one', function(){
it('should do something', function(){
})
})
})
})
describe('merge', function(){
describe('stuff', function(){
describe('two', function(){
it('should do something', function(){
})
})
})
})
describe('merge stuff', function(){
describe('three', function(){
it('should do something', function(){
})
})
})
will produce the following:
Be kind and don't make developers hunt around in your docs to figure
out how to run the tests, add a make test
target to your Makefile:
test:
./node_modules/.bin/mocha \
--reporter list
.PHONY: test
The Mocha TextMate bundle includes snippets to make writing tests quicker and more enjoyable. To install the bundle run:
$ make tm
Run mocha tests:
$ make test
Run all tests, including interfaces:
$ make test-all
Alter the reporter:
$ make test REPORTER=list
(The MIT License)
Copyright (c) 2011 TJ Holowaychuk <tj@vision-media.ca>
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
FAQs
simple, flexible, fun test framework
The npm package mocha receives a total of 7,170,639 weekly downloads. As such, mocha popularity was classified as popular.
We found that mocha demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 0 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
vlt's new "reproduce" tool verifies npm packages against their source code, outperforming traditional provenance adoption in the JavaScript ecosystem.
Research
Security News
Socket researchers uncovered a malicious PyPI package exploiting Deezer’s API to enable coordinated music piracy through API abuse and C2 server control.
Research
The Socket Research Team discovered a malicious npm package, '@ton-wallet/create', stealing cryptocurrency wallet keys from developers and users in the TON ecosystem.