首页 > 解决方案 > 如何对使用 wp.apiFetch 的古腾堡类/组件方法进行单元测试

问题描述

我正在尝试对调用 wp.apiFetch 方法的类/组件上的方法进行单元测试,但是当我运行测试时,它总是说TypeError: apiFetch is not a function以下结构适用于其他测试用例,尽管它们没有进行任何 api 调用.

精简的测试设置

global.wp = {};
// some other packages
Object.defineProperty(global.wp, 'apiFetch', { get: () => require('@wordpress/api-fetch') });

剥离测试

  1. 浅渲染组件
  2. 在组件实例上调用有问题的方法 - 此时由于顶部提到的错误,这里的测试错误。
  3. 检查方法是否被调用
  it('createAuthor valid', () => {
    // may have to mock window.fetch as wp.apiFetch uses it but that's currently not the issue

    const componentProps = {
      someFunc: jest.fn(),
    };

    const component = shallow(<NewAuthor {...componentProps} />);
    component.setState({ name: 'john smith' });

    component.instance().createAuthor();

    expect(componentProps.someFunc).toHaveBeenCalledTimes(1);
  });

剥离的组件

const { apiFetch } = wp;
// some more constants from window

class NewAuthor extends Component {
  // constructor
  // method to test
  createAuthor = () => {
    const { someFunc, someErrorFunc } = this.props;
    const authorObject = {
      name,
    } = this.state;
    const createPath = '/wp/v2/users';

    apiFetch({
      path: createPath,
      data: authorObject,
      method: 'POST',
    })
      .then((user) => {
        console.log('success', user);
        someFunc();
      })
      .catch((error) => {
        console.log('error', error);
        someErrorFunc();
      });
  };
  // some more methods
  // render
}

export default NewAuthor;

标签: wordpressjestjswordpress-gutenberg

解决方案


推荐阅读