简体   繁体   中英

Display test file name in Mocha output

Is there anyway to have mocha display the name of, or group the output by the test file ?

Given two test files, ./test/testFoo.js and ./test/testBar.js I'd like to see something like this when running mocha test :


* testFoo:

  Doing X
    ✓ should return A
    ✓ even with negative input

  Doing Y
    ✓ should return B
    ✓ should return C when called with Egyptian hieroglyphs

* testBar:

  Doing Z
    ✓ should return D

(This might be an XY problem. If there are other way to group tests in two levels, I'm just as interested. It's just that the files are already there, as a kind of natural first level group.)

I got tired of there being no solution for this every time I went searching for one and built my own reporter:

https://www.npmjs.com/package/mocha-spec-reporter-with-file-names

That page contains the details but here they are repeated:

  1. install it: npm i -D mocha-spec-reporter-with-file-names
  2. set it at your reporter
    • cli: npx mocha --reporter './node_modules/mocha-spec-reporter-with-file-names'
    • config:
       //.mocharc.js const SpecReporterWithFileNames = require('mocha-spec-reporter-with-file-names'); module.exports = { reporter: SpecReporterWithFileNames.pathToThisReporter, };

Output currently looks like this:

示例输出

You should be good using Mocha's describe method to logically group your tests. For the output you desire, the structure of your tests would look like:

/test/testFoo.js

describe('testFoo', () => {
    describe('Doing X', () => {
        it('should return A', () => {
        });

        it('even with negative input', () => {
        });
    });

    describe('Doing Y', () => {
        it('should return B', () => {
        });

        it('should return C when called with Egyptian hieroglyphs', () => {
        });
    });
});

/test/testBar.js

describe('testBar', () => {
    describe('Doing Z', () => {
        it('should return D', () => {
        });
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM