【问题标题】:ERROR: Expected mock function to have been called错误:预期的模拟函数已被调用
【发布时间】:2018-05-25 11:53:41
【问题描述】:

我正在尝试测试反应组件的跨度标记的 onClick。

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

想测试'onClick' 'changeImage' 函数是否被调用!

// test.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.

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

【问题讨论】:

  • @OluwafemiSule 谢谢,从那个链接找出我做错了什么。 :)
  • 您能否尝试存储对wrapper.instance() 的引用,而不是多次调用它来查看是否能解决问题?我想知道您是否每次都获得一个新实例

标签: javascript reactjs jestjs enzyme


【解决方案1】:

//修正错误

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 之前声明 wrapper 会导致这个错误:

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

Expected mock function to have been called.

【讨论】:

  • - 1 请解释问题出在哪里,而不是仅仅粘贴有效的代码(为什么在包装器工作后制作移动代码?)。这样一来,您的回答就会对其他人更有帮助。
  • 这不是一个好的测试,因为如果您的对象的另一个实例调用changeImage,它会给您一个误报,因为您正在监视共享原型方法。
  • @JuanMendes 你是对的。您需要清除模拟函数才能将其与其他实例正确使用。 :) 我已经编辑了我的答案。感谢您指出。
  • 您的建议将解决问题而不是修复它(您的代码可能会出现一些意想不到的后果,即在您调用 mockClear 之前,新实例确实调用了 changeImage,不太可能可能是,这只是表明您可以更好地测试它的迹象。您应该监视对象,而不是原型。我意识到我没有给您一个好的答案,只是让您知道这并不完全达到标准。
  • 我尝试监视对象,但我无法弄清楚,这是唯一对我有用的东西。如果您找到更好的方法,请告诉我。 :)
猜你喜欢
  • 2019-07-21
  • 2019-03-28
  • 2019-10-27
  • 1970-01-01
  • 2019-07-03
  • 2018-12-27
  • 1970-01-01
  • 2019-03-23
  • 2021-03-06
相关资源
最近更新 更多