最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How do I mock this method chain in Jest? - Stack Overflow

programmeradmin3浏览0评论
zoomOut(callback) {
        // Zooms out the current screen
        this.view.current.zoomOut(300).done(() => {
            (hasCallback(callback)) && callback();
        });
    }

I'm trying to test the function above but I keep getting the following error:

TypeError: this.view.current.zoomOut(...).done is not a function

How can I mock this method chain in Jest?

zoomOut(callback) {
        // Zooms out the current screen
        this.view.current.zoomOut(300).done(() => {
            (hasCallback(callback)) && callback();
        });
    }

I'm trying to test the function above but I keep getting the following error:

TypeError: this.view.current.zoomOut(...).done is not a function

How can I mock this method chain in Jest?

Share Improve this question asked Aug 20, 2018 at 0:38 j.doej.doe 1,2542 gold badges12 silver badges29 bronze badges 1
  • This is not a method chain, it just invokes the method on a deeply nested object. – Lin Du Commented Aug 13, 2019 at 14:56
Add a ment  | 

2 Answers 2

Reset to default 3

Thanks to BudgieInWA, I was able to solve this problem by returning done.

For those who are testing a React ponent with Enzyme, here's how you can do it:

it('should call callback', () => {
    const wrapper = shallow(<Zoom {...minProps}/>);
    const instance = wrapper.instance();

    const callback = jest.fn();

    instance.view = {
        current: {
            zoomOut: jest.fn(() => {
                return {
                    done: jest.fn((callback) => {
                        callback();
                    })
                };
            })
        }
    };

    expect(callback).toHaveBeenCalledTimes(0);
    instance.zoomOut(callback);
    expect(callback).toHaveBeenCalledTimes(1);
});

You could try this:

const mockZoomOut = jest.fn(() => ({ done(cb) { cb(); } }));
const mockThis = {
    view: {
        current: {
            zoomOut: mockZoomOut,
        },
    },
};

test('it does', () => {
    const cb = jest.fn();
    zoomOut.apply(mockThis, [cb]);
    expect(mockZoomOut).toHaveBeenCalledTimes(1);
    expect(cb).toHaveBeenCalledTimes(1);
});

See Jest Mock Functions and fn.apply.

If you are testing the behaviour of the class as a whole, then you could set up the instance that you are testing to have this.view.current.zoomOut be mockZoomOut somehow.

发布评论

评论列表(0)

  1. 暂无评论