Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

mochawesome

adamgruber5.5mMIT7.1.3TypeScript support: definitely-typed

A gorgeous reporter for Mocha.js

mocha, reporter, json, html

readme

mochawesome

npm Node.js CI Gitter

Mochawesome is a custom reporter for use with the Javascript testing framework, mocha. It runs on Node.js (>=10) and works in conjunction with mochawesome-report-generator to generate a standalone HTML/CSS report to help visualize your test runs.

Features

Mochawesome Report
  • Simple, clean, and modern design
  • Beautiful charts (via ChartJS)
  • Support for test and suite nesting
  • Displays before and after hooks
  • Review test code inline
  • Stack trace for failed tests
  • Support for adding context information to tests
  • Filters to display only the tests you want
  • Responsive and mobile-friendly
  • Offline viewing
  • Supports parallel mode

Usage

  1. Add Mochawesome to your project:

npm install --save-dev mochawesome

  1. Tell mocha to use the Mochawesome reporter:

mocha testfile.js --reporter mochawesome

  1. If using mocha programatically:
var mocha = new Mocha({
  reporter: 'mochawesome',
});

Parallel Mode

Since mocha@8 test files can be run in parallel using the --parallel flag. In order for mochawesome to work properly it needs to be registered as a hook.

mocha tests --reporter mochawesome --require mochawesome/register

Output

Mochawesome generates the following inside your project directory:

mochawesome-report/
├── assets
│   ├── app.css
│   ├── app.js
│   ├── MaterialIcons-Regular.woff
│   ├── MaterialIcons-Regular.woff2
│   ├── roboto-light-webfont.woff
│   ├── roboto-light-webfont.woff2
│   ├── roboto-medium-webfont.woff
│   ├── roboto-medium-webfont.woff2
│   ├── roboto-regular-webfont.woff
│   └── roboto-regular-webfont.woff2
├── mochawesome.html
└── mochawesome.json

The two main files to be aware of are:

mochawesome.html - The rendered report file

mochawesome.json - The raw json output used to render the report

Options

Options can be passed to the reporter in two ways.

Environment variables

The reporter will try to read environment variables that begin with MOCHAWESOME_.

$ export MOCHAWESOME_REPORTFILENAME=customReportFilename

Note that environment variables must be in uppercase.

Mocha reporter-options

You can pass comma-separated options to the reporter via mocha's --reporter-options flag. Options passed this way will take precedence over environment variables.

$ mocha test.js --reporter mochawesome --reporter-options reportDir=customReportDir,reportFilename=customReportFilename

Alternately, reporter-options can be passed in programatically:

var mocha = new Mocha({
  reporter: 'mochawesome',
  reporterOptions: {
    reportFilename: 'customReportFilename',
    quiet: true,
  },
});

Available Options

The options below are specific to the reporter. For a list of all available options see mochawesome-report-generator options.

Option Name Type Default Description
quiet boolean false Silence console messages
reportFilename string mochawesome Filename of saved report (html and json)
See notes for available token replacements.
html boolean true Save the HTML output for the test run
json boolean true Save the JSON output for the test run
consoleReporter string spec Name of mocha reporter to use for console output, or none to disable console report output entirely

reportFilename replacement tokens

Using the following tokens it is possible to dynamically alter the filename of the generated report.

  • [name] will be replaced with the spec filename when possible.
  • [status] will be replaced with the status (pass/fail) of the test run.
  • [datetime] will be replaced with a timestamp. The format can be - specified using the timestamp option.

For example, given the spec cypress/integration/sample.spec.js and the following config:

{
  reporter: "mochawesome",
  reporterOptions: {
    reportFilename: "[status]_[datetime]-[name]-report",
    timestamp: "longDate"
  }
}

The resulting report file will be named pass_February_23_2022-sample-report.html

Note: The [name] replacement only occurs when mocha is running one spec file per process and outputting a separate report for each spec. The most common use-case is with Cypress.

Adding Test Context

Mochawesome ships with an addContext helper method that can be used to associate additional information with a test. This information will then be displayed inside the report.

Please note: arrow functions will not work with addContext. See the example.

addContext(testObj, context)

param type description
testObj object The test object
context string|object The context to be added to the test

Context as a string

Simple strings will be displayed as is. If you pass a URL, the reporter will attempt to turn it into a link. If the URL links to an image or video, it will be shown inline.

Context as an object

Context passed as an object must adhere to the following shape:

{
  title: 'some title'; // must be a string
  value: {
  } // can be anything
}

Example

Be sure to use ES5 functions and not ES6 arrow functions when using addContext to ensure this references the test object.

const addContext = require('mochawesome/addContext');

describe('test suite', function () {
  it('should add context', function () {
    // context can be a simple string
    addContext(this, 'simple string');

    // context can be a url and the report will create a link
    addContext(this, 'http://www.url.com/pathname');

    // context can be an image url and the report will show it inline
    addContext(this, 'http://www.url.com/screenshot-maybe.jpg');

    // context can be an object with title and value properties
    addContext(this, {
      title: 'expected output',
      value: {
        a: 1,
        b: '2',
        c: 'd',
      },
    });
  });
});

It is also possible to use addContext from within a beforeEach or afterEach test hook.

describe('test suite', () => {
  beforeEach(function () {
    addContext(this, 'some context');
  });

  afterEach(function () {
    addContext(this, {
      title: 'afterEach context',
      value: { a: 1 },
    });
  });

  it('should display with beforeEach and afterEach context', () => {
    // assert something
  });
});

Typescript

This project does not maintain its own type definitions, however they are available on npm from DefinitelyTyped.

$ npm install --save-dev @types/mochawesome

mochawesome-report-generator

License

mochawesome is MIT licensed.

changelog

mochawesome changelog

Unreleased

7.1.3 - 2022-03-25

Changed

  • Bump marge to 6.2.0 #372

Fixed

  • Unhandled TypeError attempting to set filename of empty suite #373

7.1.2 - 2022-03-05

Changed

  • Bump marge to 6.1.1 to fix #195

    7.1.1 - 2022-03-03

    Fixed

  • Add fallback when attempting to set file and fullFile on root suite. #371

7.1.0 - 2022-02-24

Added

  • Support for [name] replacement token in reportFilename option

Changed

  • Bump mochawesome-report-generator to 6.1.0

7.0.1 - 2021-11-05

Changed

  • Bump marge to 6.0.1 to fix #363

7.0.0 - 2021-11-03

Changed

  • BREAKING Update mochawesome-report-generator to 6.0.0 (Drops support for Node<12)
  • Update strip-ansi dependency to latest non-ESM version
  • Update chalk dependency

6.3.1 - 2021-10-06

Fixed

  • Ignore retriedTest serialization to avoid circular issues #356

6.3.0 - 2021-09-29

Changed

  • Update parallel processing so output JSON matches sync runs #353
  • Update how the total number of skipped tests is calculated #317

6.2.2 - 2021-02-16

Changed

  • Greenkeep dependencies

6.2.1 - 2020-11-02

Fixed

  • Add register.js to "files" array

6.2.0 - 2020-11-01

Added

  • Support mocha --parallel mode

Changed

  • Update dev dependencies
  • Remove airbnb-extended eslint config. Use eslint:recommended instead
  • Add husky, lint-staged, and prettier
  • Format all files with prettier
  • Remove travis-ci config

6.1.1 - 2020-04-27

Fixed

  • Restore inline-diff rendering #312

6.1.0 - 2020-04-13

Changed

  • Bump mochawesome-report-generator to 5.1.0. No longer requires react or react-dom as peer deps

6.0.0 - 2020-04-10

Changed

  • BREAKING Bump mochawesome-report-generator to 5.0.0 (Requires react and react-dom be installed separately)
  • Update all other dependencies

5.0.0 - 2020-02-25

Changed

  • BREAKING Drop support for node 8
  • BREAKING Requies mocha 7+

Fixed

  • Ensure a stats collector is always initialized
  • Omit code snippets from JSON when code option is false

4.1.0 - 2019-08-06

Added

  • New consoleReporter option to allow specifying console reporter to use or disabling console reporter entirely #99

4.0.1 - 2019-06-15

Fixed

  • Issue where using addContext inside a before or after hook would incorrectly apply context to the test #284

4.0.0 - 2019-06-04

  • Breaking changes to JSON data structure:
  • Renamed allSuites to results and made it an array of suites
  • Removed isRoot property from cleaned tests (only suites can be a root)
  • Removed class-related stats (passPercentClass, pendingPercentClass)
  • Added uuid to suites
  • Removed rounding of passPercent and pendingPercent
  • Removed copyrightYear property
  • Added new meta property to track info about the test run (useful for debugging)

Changed

  • Drop support for Node <8
  • Require peer dependency of mocha >5
  • Removed Babel dependency
  • Replace lodash dependency with individual modules
  • Updated codeclimate config to version 2
  • Updated various dependencies

3.1.2 - 2019-04-17

Fixed

  • Issue where a suite with skipped tests reports duration as 0. #276

3.1.1 - 2018-10-22

Changed

  • Switch from RegExp to state machine for stripping function start in cleanCode method. #257

3.1.0 - 2018-10-17

Changed

  • Invert logic for getting test code by checking for test.body before test.fn inside cleanTest method #252

3.0.3 - 2018-07-25

Changed

  • Reworked cleanCode regexes to handle more cases #244

3.0.2 - 2018-01-25

Changed

  • Call stripAnsi for test/suite titles. #223 (@JoeTheFkingFrypan)

3.0.1 - 2017-12-26

Fixed

  • Updated RegExp in cleanCode method to handle arrow functions without braces. #220

3.0.0 - 2017-11-30

This release is in tandem with and requires mochawesome-report-generator >= 3.0.0.

Added

  • New option: html. Allows user to specify whether or not to generate the HTML report. Defaults to true.

Changed

  • BREAKING: This release features a trimmed-down data output that removes properties that are not necessary for the report generation. This change will only affect things that consume the JSON output and does not affect usage of the reporter itself.
  • Suites are now cleaned by mapping over them instead of a breadth-first traversal
  • Options handling was overhauled and greatly simplified. The reporter will only concern itself with options directly related to the reporter. All other options are passed through to the report generator as-is.
  • Updated the done function to display better output when only one or no files have been generated.

Removed

  • enableTestCode option was deprecated as of 2.0.3 and has been removed. Use enableCode instead.

2.3.1

Fixed

  • Fixes an issue where generator functions were not displayed properly #188 (@APshenkin)

2.3.0

Added

  • Added showHooks option #168
  • Support mocha's --inline-diffs option #167
  • Normalize error objects for consistent display #166
  • Bumped mochawesome-report-generator dependency to 2.2.0

2.2.1

Changed

  • Separated out before and after hooks
  • Bumped mochawesome-report-generator dependency to 2.1.0

2.2.0

Changed

  • Enable using addContext in beforeEach and afterEach test hooks
  • Fix a bug where you could pass an object with empty title string to addContext
  • Allow a context value of undefined to be displayed in the report

2.1.0

Added

  • Added new options: overwrite and timestamp

2.0.5

Fixed

  • Fix UnhandledPromiseRejectionWarning error when calling nonexistant exit function
  • Limit files included in package

2.0.4

Changed

  • Better handling of different coding styles in test code. #98
  • Separate utility functions from main reporter code for better test coverage
  • Bump mochawesome-report-generator and fs-extra packages

2.0.3

Added

  • Add enableCode option to be consistent with mochawesome-report-generator options
  • Add dev option for testing

Changed

  • Deprecate enableTestCode option

Fixed

  • Fixed #126
  • Fix default options handling

2.0.2

Fixed

2.0.1

Fixed

  • Fixed an issue where reportFilename was not propagated to config object
  • Updated handling of reportDir option to allow relative paths
  • Bumped mochawesome-report-generator dependency (requires 1.0.3 or higher)

2.0.0

Changed

  • Moved report generation to mochawesome-report package
  • Updated dependencies
  • Switched from jshint to eslint
  • Rewritten using ES6
  • Fixed an issue where test uuid was not generated properly
  • Added done function that will get called before mocha exits (eliminates need for --no-exit option)
  • Unit tests!
  • Added diff for test error
  • Added ability to display additional test context
  • Breaking reportName option changed to reportFilename

1.5.4

Changed

  • Run pending tests thru cleanTest function. Fixes possible scenario where a pending test with a large amount of text could cause node to run out of memory. See #94

1.5.3

Fixed

  • Fixed build issues on Windows. See #84

1.5.2

Changed

  • Updated mocha peerDependency to allow any version

1.5.1

Added

  • Added missing LICENSE.md file

1.5.0

Changed

  • Moved mocha to peerDependencies and devDependencies and fixed it to ~2. See #69

1.4.0

Added

  • Added slide-over navigation menu for quickly jumping to a test suite. See #49

1.3.5

Fixed

  • Removed extra slash in @font-path LESS variable. See #53

1.3.4

Added

  • Added option to auto open report. Also fixed an issue with boolean options. See #44

1.3.3

Added

  • Added support for creating custom dir where the parent dir(s) may not exist yet. See #40

1.3.2

Fixed

  • Removed allHooks array since it was not being used and could lead to an issue where node runs out of memory while rendering the template. See #33

1.3.1

Changed

  • Update copyright in template

1.3.0

Fixed

  • Changes to support mocha 2.4.0 and later (fixes empty code blocks). See #29

1.2.2

Added

  • Added option to generate report with all assets inlined. See #26

1.2.1

Fixed

  • Reset totalTestsRegistered when reporter is run. PR #21

1.2.0

Added

  • Enhancement: custom report title option. Closes #11

Fixed

  • Fixed indentation in code block and stack traces

1.1.2

Fixed

1.1.1

Added

  • Add filter icon in summary for better visibility (Completely new idea and not at all in response to this)

Changed

1.1.0

Added

  • Add support for options
  • custom report directory
  • custom report filename
  • Enhancements to console output

1.0.5

Changed

  • Bugfixes

1.0.0

Added

  • Redesigned report
  • Mobile friendly
  • Complete refactor of client-side script
  • Custom builds of vendor scripts
  • Custom font-icon set
  • All fonts are now local to the report