JSX 单元测试中有 Mock

Jest Mock inside a JSX Unit Test

我有一个 JSX 文件来编写 jest 单元测试。

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

在测试文件中,

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

我收到以下错误。

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

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

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

这是一个使用 Jest 的粗略示例。它直接使用 built-in 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')
        });
    });
});