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!

July 23, 2019

How to add a checkbox in primereact datatable

Code snippet to add a checkbox in each row of a primereact datatable.

import React, { Component } from 'react';
import {DataTable} from 'primereact/datatable';
import {Column} from 'primereact/column';

export class DTColumnCheckBoxDemo extends Component {

    constructor() {
        super();
        this.state = {
        }
    }
    render() {
       return (
         <DataTable value={this.state.list}}
            selection={this.state.listItem} onSelectionChange={(e) => this.setState({listItem: e.data})} >
            <Column em="" selectionmode="multiple" />
            <Column field="xyz" header="XYZ" />
            <Column field="abc" header="ABC" />
         </DataTable>
    );
}

In Column tag we need to add selectionmode  attribute to add checkbox in datatable.