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

zoomOut(callback) { Zooms out the current screenthis.view.current.zoomOut(300).done(() => {(hasCal

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.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744177008a4561801.html

相关推荐

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

    zoomOut(callback) { Zooms out the current screenthis.view.current.zoomOut(300).done(() => {(hasCal

    9天前
    30

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信