首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何测试方法是否在componentDidMount内部被调用?

如何测试方法是否在componentDidMount内部被调用?
EN

Stack Overflow用户
提问于 2019-05-03 23:05:47
回答 1查看 670关注 0票数 4

我有以下componentDidMount生命周期:

代码语言:javascript
复制
componentDidMount () {
    window.scrollTo(0, 0);

    this.setState({
      loading: true,
    });

    if (token) return this.getUserData();
    return this.guestUserData();
  }

我想在jest/酶中测试componentDidMount是否运行,guestUserData是否被调用。

我写了以下测试:

代码语言:javascript
复制
test("should call method in componentDidMount", () => {
    Component.prototype.guestUserData = jest.fn();
    const spy = jest.spyOn(Component.prototype, 'guestUserData');

    const wrapper = shallow(<Component {...defaultProps} />);
    expect(spy).toHaveBeenCalled();
  });

但我现在有个错误:

代码语言:javascript
复制
TypeError: Cannot set property guestUserData of #<Component> which has only a getter

如果可能的话,有人可以建议如何测试方法是否在生命周期中调用,以及生命周期本身是否在一次测试中调用

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-05-04 05:52:55

我相信getUserData正在调用一些外部应用程序接口(而不是发送XHR或使用会话存储或其他什么)。因此,您只需模拟外部源,并在创建组件后立即验证它是否已被访问

代码语言:javascript
复制
const fetchUserData = jest.fn();

jest.mock('../api/someApi', () => ({
    fetchUserData,
}));

beforeEach(() => {
    fetchUserData.mockClear();
});

it('calls API on init', () => {
    shallow(<Yourcomp {...propsItNeeds} />);
    expect(fetchUserData).toHaveBeenCalledWith(paramsYouExpect);
});

it('does something if API call fails', () => {
    fetchUserData.mockRejectedValue();
    const wrapper = shallow(<Yourcomp {...propsItNeeds} />);
    expect(wrapper.find(ErrorMessage).props().children).toEqual('Failed to load. Try again');
    // or even
    expect(wrapper).toMatchSnapshot();
});

这样你就可以真正地测试是否1.外部API已经在组件init上被调用了2. API已经被调用了预期的参数3.组件知道如果API调用失败该怎么做4 . .

相反,检查cDM中是否调用了this.getUserData方法并不能确保上面的任何一项。如果this.getUserData本身不调用API怎么办?如果API故障在那里没有得到正确的处理,该怎么办?我们仍然不能确定这一点。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55972552

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档