gpt4 book ai didi

javascript - 错误 : Expected mock function to have been called

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:25:06 24 4
gpt4 key购买 nike

我正在尝试测试 React 组件的 span 标签的 onClick。

<span id="A" onClick={this.changeImage}> Image A</span>

想测试是否调用了“onClick”和“changeImage”函数!

//测试.js

describe('Tests', () => {
const wrapper = shallow(<Image />);
it('Should render without exploading', () => {
expect(wrapper).toHaveLength(1);
});

it('Should call changeImage() function on click', () => {
wrapper.instance().changeImage = jest.fn();
wrapper.update();
wrapper.find('#A').simulate('click', { target: { id: 'A' } });
expect(wrapper.instance().changeImage).toHaveBeenCalled();
});
});

也试过这个 -

it('Should call changeImage() function on click', () => {
const spy = jest.spyOn(wrapper.instance(), 'changeImage');
wrapper.find('#A').simulate('click', { target: { id: 'A' } });
expect(spy).toHaveBeenCalled();
});

两者都返回相同的错误。//错误

● Tests › Should call changeImage() function on click

expect(jest.fn()).toHaveBeenCalled()

Expected mock function to have been called.

有人可以指出我做错了什么吗?谢谢。

最佳答案

//修正错误

describe('Tests', () => {
it('Should render without exploading', () => {
const wrapper = shallow(<Image />);
expect(wrapper).toHaveLength(1);
});

it('Should call changeImage() function on click', () => {
const spy = jest.spyOn(Image.prototype, 'changeImage');
const wrapper = shallow(<Image/>);
wrapper.find('#A').simulate('click', { target: { id: 'A' } });
expect(spy).toHaveBeenCalled();
spy.mockClear();//clearing the mock functions
});
});

在 jest.spyOn() 模拟函数之后放置包装器使测试成功。

在模拟函数的情况下,声明 const 的顺序很重要。需要先声明 spy ,然后再声明包装器。在 spy 之前声明包装器将导致此错误:

expect(jest.fn()).toHaveBeenCalled()

Expected mock function to have been called.

关于javascript - 错误 : Expected mock function to have been called,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47761728/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com