Skip to content

armgit / mocha

Public Imported from GitHub
0

☕️ Classic, reliable, trusted test framework for Node.js and the browser

docs: migrate Spies wiki page to explainers (#5420)

Kelechi Ebiricbcf007c5ae2
diff --git a/docs-next/astro.config.ts b/docs-next/astro.config.ts
index 3d50540a..dfa38ca5 100644
--- a/docs-next/astro.config.ts
+++ b/docs-next/astro.config.ts
@@ -106,6 +106,10 @@ export default defineConfig({
label: "Shared behaviours",
slug: "explainers/shared-behaviours",
},
+ {
+ label: "Spies",
+ slug: "explainers/spies",
+ },
{ label: "Test duration", slug: "explainers/test-duration" },
{
label: "Test fixture decision tree",
diff --git a/docs-next/src/content/docs/explainers/spies.mdx b/docs-next/src/content/docs/explainers/spies.mdx
new file mode 100644
index 00000000..b455f440
--- /dev/null
+++ b/docs-next/src/content/docs/explainers/spies.mdx
@@ -0,0 +1,60 @@
+---
+description: How to use spies with Mocha for testing callbacks and function calls
+title: Spies
+---
+
+Mocha does not come equipped with spies, though libraries like [Sinon](https://github.com/sinonjs/sinon) provide this behaviour if desired. The following is an example of Mocha utilizing Sinon and [Should.js](https://github.com/shouldjs/should.js) to test an EventEmitter:
+
+```javascript
+var sinon = require('sinon'),
+ EventEmitter = require('events').EventEmitter;
+
+describe('EventEmitter', function() {
+ describe('#emit()', function() {
+ it('should invoke the callback', function() {
+ var spy = sinon.spy(),
+ emitter = new EventEmitter();
+
+ emitter.on('foo', spy);
+ emitter.emit('foo');
+ spy.called.should.equal.true;
+ })
+
+ it('should pass arguments to the callbacks', function() {
+ var spy = sinon.spy(),
+ emitter = new EventEmitter();
+
+ emitter.on('foo', spy);
+ emitter.emit('foo', 'bar', 'baz');
+ sinon.assert.calledOnce(spy);
+ sinon.assert.calledWith(spy, 'bar', 'baz');
+ })
+ })
+})
+```
+
+The following is the same test, performed without any special spy library, utilizing the Mocha `done([err])` callback as a means to assert that the callback has occurred, otherwise resulting in a timeout. Note that Mocha only allows `done()` to be invoked once, and will otherwise error.
+
+```javascript
+describe('EventEmitter', function() {
+ describe('#emit()', function() {
+ it('should invoke the callback', function(done) {
+ var emitter = new EventEmitter();
+
+ emitter.on('foo', done);
+ emitter.emit('foo');
+ })
+
+ it('should pass arguments to the callbacks', function(done) {
+ var emitter = new EventEmitter();
+
+ emitter.on('foo', function(a, b) {
+ a.should.equal('bar');
+ b.should.equal('baz');
+ done();
+ });
+ emitter.emit('foo', 'bar', 'baz');
+ })
+ })
+})
+```