wordpress - 如何对使用 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') });
剥离测试
- 浅渲染组件
- 在组件实例上调用有问题的方法 - 此时由于顶部提到的错误,这里的测试错误。
- 检查方法是否被调用
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;
解决方案
推荐阅读
- java - 如何将这种广度优先搜索转换为 Java 中的静态方法?
- javascript - 找不到模块“../constants/links”的声明文件 | src/constants/links.js' 隐含一个 'any' 类型
- php - 会话值到数组
- python - 如何在 JSON 文件中按字母顺序按一个字符串对列表进行排序
- html - 如何解决具有背景 div 的 2 列布局中的高度自动问题
- python - 将 Selenium CSV 下载到 python 变量中
- python - 将高度作为值放入另一列
- c# - 在 C# 中使用 APNS 推送进行编码
- javascript - TypeError:无法读取未定义的属性“oldRole”
- angular - 返回成功的 Observable On Route Resolve Call Failure?