user3686652
user3686652

Reputation: 815

Jest Mock inside a JSX Unit Test

I have one JSX file to write jest Unit Test.

../dist/container/index

constructor(props) {
super(props);
this.state = {
    showName: null
}
}

componentWillMount() {
        Request
            .get('/api')
            .end((err, res) => {
                if (res) {
                    this.setState({
                        showName: res.name
                    });
                }
            });
    }

render (
    let { showName } = this.state;
    render (
    {showName ? <div> showName</div> : <div>No Name</div> }
)
)

In test File,

import landing from '../dist/container/index’;
describe(‘landing’, () => {
it(‘check’, () => { 
jest.mock('../dist/container/index’, () => {});
       landing.componentWillMount = jest.fn().mockImplementation(() => { return { 'a': '2'} });
        const lands = shallow(<landing productDetails={productDetail} messages={messages}/>);
expect(lands.componentWillMount()).toBeCalledWith({‘a’: '2'});
})
});

I am getting the below error.

expect(jest.fn())[.not].toBeCalledWith()

jest.fn() value must be a mock function or spy. Received: object: {"a": "2"}

I want to mock the whole componentwillmount calls and need to get the showName, but i am always getting No Name. Any support?

Upvotes: 0

Views: 1386

Answers (1)

dashton
dashton

Reputation: 2714

Here is a rough example using Jest. It uses the built-in Fetch API directly and mocks that using jest's mockImplementation.

I've assumed you are using enzyme for validating component output.

Landing.jsx

  import React from "react";
import { render } from "react-dom";


export class Landing extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            showName: null
        };

    }

    componentDidMount() {
        fetch("/api", {
            method: 'GET'
        })
        .then(res => {
            this.setState({
                showName: res.name
            });
        })
        .catch (err => { /* do something */ });
    }

    render() {
        const { showName } = this.state;
        const displayName = showName ? showName : "No Name";
        return <div id='show'>{displayName}</div>;
    }
}

Landing.spec.js

import React from 'react';
import ReactDOM from 'react-dom';
import { Landing, http } from "./landing";
import Enzyme, { shallow } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';

Enzyme.configure({ adapter: new Adapter() });

describe("<Landing />", () => {
    let wrapper;

    describe("when api returns successfully", () => {
        beforeEach(() => {
            window.fetch = jest.fn().mockImplementation(() => {
                return Promise.resolve({
                    name: 'foo'
                })
            })
            wrapper = shallow(<Landing />);
        })

        it ('should render foo', () => {
            expect(wrapper.update().find('div').text()).toEqual('foo')
        });
    });

    describe("when api returns unsuccessfully", () => {
        beforeEach(() => {
            window.fetch = jest.fn().mockImplementation(() => {
                return Promise.reject("err")
            })
            wrapper = shallow(<Landing />);
        })

        it ('should render No Name', () => {
            expect(wrapper.update().find('div').text()).toEqual('No Name')
        });
    });
});

Upvotes: 0

Related Questions