1

I have scenario like this:

const isBrowser = new Function("try {return this===window;}catch(e){ return false;}");

if(isBrowser){
//Run browser specific code
}else {
 // run nodejs specific code
}

I am setting up a test environment using Mocha, Chai and istanbul. How can i setup in such a way that few test suits should run on browser and few on NodeJs.

The goal is to get the combined coverage report.

how can I configure the Mocha to run in both browser and in NodeJs environment, using karma or without karma ?

for example:

//this should run in NodeJS Environment
describe('Loader Node Js', () => {
    it('Load files from File system', (done) => {
        loader.load('file path')
            .then((files) => {
                done();
            });
    });
});

//this should run in Browser Environment
describe('Loader Browser', () => {   
    it('Load files from Server AJAX', (done) => {
        loader.load('file url')
            .then((files) => {

                done();
            });
    });

})

Apurva Ojas
  • 331
  • 1
  • 5

1 Answers1

1

You should be able to test for Node.js and browser specific globals in your suite.

if (typeof module === 'object') {

    //this should run in NodeJS Environment
    describe('Loader Node Js', () => {
        it('Load files from File system', (done) => {
            loader.load('file path')
                .then((files) => {
                    done();
                });
        });
    });

} else {

    //this should run in Browser Environment
    describe('Loader Browser', () => {   
        it('Load files from Server AJAX', (done) => {
            loader.load('file url')
                .then((files) => {
                    done();
                });
        });
    })
}

You have other options, too, like testing for typeof self === 'undefined', which is true in Node.js and false in a browser.

There are a few related question you may find interesting:

GOTO 0
  • 42,323
  • 22
  • 125
  • 158