Mocha tests with extra options or parameters

后端 未结 10 1943
一向
一向 2020-12-04 16:17

I am writing test cases for my Node.js application using Mocha. The test cases need an API key as an extra input option or parameter. The API key is private, so I don\'t wan

10条回答
  •  一整个雨季
    2020-12-04 17:09

    The other answers are limited in that they do not support code execution prior to running your test suite. They only support passing parameters.

    This answer supports code execution BEFORE your test suite is executed and is fully documented by mocha

    mocha docs: http://unitjs.com/guide/mocha.html#mocha-opts

    create ./test/mocha.opts

    --recursive
    --reporter spec
    --require ./server.bootstrap
    --require ./test/test.bootstrap
    

    create ./server.bootstrap.js

    global.appRoot = require('app-root-path');
    // any more server init code
    

    create ./test/test.bootstrap.js

    process.env.NODE_ENV='test';
    // any more test specific init code
    

    finally in your server.js:

    require('./server.bootstrap');
    

    DONE!

    The code in the server bootstrap will be executed prior to testing and server execution (npm start and npm test)

    The code in the test bootstrap will only be executed prior to testing (npm test)

    Thanks to @damianfabian for this one - see How to initialise a global variable in unit test runs?

提交回复
热议问题