Sha*_*dul 8 javascript unit-testing typeerror reactjs jestjs
我正在尝试使用 Jest 作为测试运行程序为我的 React 应用程序编写测试用例(默认创建 react 应用程序配置)。我正在模拟调用 API 的方法,方法是使用mocks文件夹存储一个文件,其中包含返回用 API 数据解析的 Promise 的方法。我的组件使用 await 关键字在异步方法中调用这些 API 处理方法。async/await 包含在 try catch 中。来自 API 方法的响应用于更新状态。响应来了,甚至可以在 console.log 中看到,但是使用此响应后的立即 setState 会引发以下错误:
'TypeError: 无法读取 null 的属性 'createEvent'
并且有一个警告:'警告:无法在现有状态转换期间更新(例如在渲染中)。Render 方法应该是 props 和 state 的纯函数。
有趣的是我有 5 个单独的 API 调用,除此 API 调用外,所有其他 4 个都成功更新了它们的状态。
我的代码中有 API 调用,这个特定的组件有 5 个 API 调用。我的代码结构是这样的,有一个名为 services.js 的文件,其中包含执行 API 调用的方法。
// src/services.js
// A method for making POST calls
export const postData = (url, data) => {
return fetch(url, {
method: 'POST',
body: data,
headers
}).then(fetchErrorHandler);
}
// Method to handle response of the API calls
export const fetchErrorHandler = response => {
if (response.ok) {
return response;
} else {
const err = new Error();
err.status = response.status;
err.response = response;
if (response.status === 400) {
err.body = response.json().then(body => body);
}
throw err;
}
};
// Actual method used for doing this particular API call
export const makeSampleAPICall = () => {
return postData(URL, formData).then(resp => resp.json());
}
Run Code Online (Sandbox Code Playgroud)
我在我的组件中使用它如下:
async fetchSomeData() { // This is a bound class method getting called.
try {
const response = await makeSampleAPICall();
const { data } = response;
this.setState({ previousAnnotations: data });
} catch (e) {
console.error(e);
}
}
Run Code Online (Sandbox Code Playgroud)
我的测试用例是一个简单的深度渲染:
it('deep renders component', () => {
mount(<MyComponent />);
}
Run Code Online (Sandbox Code Playgroud)
还有我的模拟 API 方法:
// src/__mocks__/services.js
export function makeSampleAPICall() {
return new Promise(resolve => {
resolve({
data: [{ some: 'data' }]
});
});
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1929 次 |
| 最近记录: |