在JSX单元测试中的Jest Mock

时间:2018-02-18 14:45:23

标签: reactjs unit-testing jest babel-jest

我有一个JSX文件来编写jest Unit Test。

../ DIST /容器/索引

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> }
)
)

在测试文件中,

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'});
})
});

我收到以下错误。

  

期望(jest.fn())[不] .toBeCalledWith()

     

jest.fn()值必须是模拟函数或间谍。收稿日期:       对象:{“a”:“2”}

我想模拟整个componentwillmount调用并需要获取showName,但我总是得到No Name。任何支持?

1 个答案:

答案 0 :(得分:0)

以下是使用Jest的粗略示例。它直接使用内置的Fetch API,并使用jest的mockImplementation进行模拟。

我假设您正在使用enzyme来验证组件输出。

<强> 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')
        });
    });
});