Showing posts with label UnitTesting. Show all posts
Showing posts with label UnitTesting. Show all posts

October 30, 2019

How to mock third party libraries and functions in jest using react js


Jest is a library we use for testing JS code whether it's an Angular application or React JS.

Many times we encounter issues while testing code which has third party libraries like mixpanel, moment, redux etc.

To resolve, we need to mock these 3rd party libraries and their respective functions. We need to intercept these libraries by mocking as given below:

1) Create a directory at root as "__mocks__".
2) Let say we need to create mock for moment library. Create a JS file under __mocks__ as moment.js. Keep in mind to have the file name exactly same as declared when importing in source code.
3) Open moment.js file and write below code snippet

const moment = {
  anyFunc: jest.fn()
}
export default moment;

4) Now execute your jest test cases. It will not throw error for moment library.
5) Use can add any mock functions in that file and add expected response and test them.

Hope this helps!

March 25, 2018

How to config gulp to run unit test cases using Istanbul with code coverage

Add below configuration in gulpfile.js for running Istanbul with mocha unit test cases through gulp.


const gulp = require('gulp');
const istanbul = require('gulp-istanbul');
const mocha = require('gulp-mocha');

gulp.task('test', () => {    
 gulp.src(['src/**/*.js'])
    .pipe(istanbul())
    .pipe(istanbul.hookRequire())
    .on('finish', () => {
      gulp.src(['test/unit/**/*.spec.js'])
        .pipe(mocha())
        .pipe(istanbul.writeReports({
          dir: './test/unit-test-coverage',
          reporters: ['lcov', 'clover', 'text', 'text-summary'],
          reportOpts: {
            dir: './test/unit-test-coverage',
          },
        }));        
    });
 });


For code coverage, we can use istanbul.writeReports method as shown above.

Once executing the command gulp test, it will execute all the test cases along with coverage report generated at given location.

Running Jest using Gulp with code coverage

Jest is a unit test framework that is mainly used for reactjs. Jest is widely used by facebook in their projects.

Add below configuration in gulpfile.js for running Jest unit test cases through gulp


  const gulp = require('gulp');
  const jestcli = require('jest-cli');

  gulp.task('test', () => {  
   jestcli.runCLI({ config: { rootDir: 'test/unit/' } }, '.', (done) => {
    done();
   });
  });

Using command: gulp test, will execute the test cases written under directory 'test/unit'. To have code coverage, we can configure it in package.json file as below:

  "jest": {
    "collectCoverage": true,
    "coverageDirectory": "./test/unit-test-coverage"
  }

Add above config in package.json file. for defining custom directory to create the report, mention the directory in coverageDirectory key, otherwise it will generate at root directory.