【发布时间】:2019-06-08 18:42:37
【问题描述】:
我正在尝试为反应组件编写单元测试。这是一个相当标准的组件,它调用一个 promise-returning 方法并使用 'then' 和 'catch' 来处理分辨率。我的测试试图验证它是否在 promise 被拒绝时调用了正确的方法,但是尽管遵循了我认为是标准模式的方法,但我无法开玩笑地验证调用。我在这里列出了相关文件,并且还提供了一个 github 示例,该示例链接在问题的底部。该示例只是一个使用 npx 创建的新反应应用程序,并添加了以下文件。
这是我的示例组件:
import React from 'react';
import api from '../api/ListApi';
class ListComponent extends React.Component {
constructor(props) {
super(props);
this.fetchListSuccess = this.fetchListSuccess.bind(this);
this.fetchListFailed = this.fetchListFailed.bind(this);
}
fetchList() {
api.getList()
.then(this.fetchListSuccess)
.catch(this.fetchListFailed);
}
fetchListSuccess(response) {
console.log({response});
};
fetchListFailed(error) {
console.log({error});
};
render() {
return(<div>Some content</div>);
};
}
export default ListComponent;
这是 api 类(注意,如果您运行应用程序,则该 api 不存在,例如,它就在这里):
const getList = () => fetch("http://someApiWhichDoesNotExist/GetList");
export default { getList };
这是测试用例:
import ListComponent from './ListComponent';
import api from '../api//ListApi';
describe('ListComponent > fetchList() > When the call to getList fails', () => {
it('Should call fetchListFailed with the error', async () => {
expect.hasAssertions();
//Arrange
const error = { message: "some error" };
const errorResponse = () => Promise.reject(error);
const componentInstance = new ListComponent();
api.getList = jest.fn(() => errorResponse());
componentInstance.fetchListFailed = jest.fn(() => { });
//Act
componentInstance.fetchList();
//Assert
try {
await errorResponse;
} catch (er) {
expect(componentInstance.fetchListFailed).toHaveBeenCalledWith(error);
}
});
});
问题是测试没有执行 catch 块,所以在这种情况下,expect.hasAssertions() 没有通过测试。谁能帮我理解 catch 块没有执行?在 try 块中包装 await 并在 catch 中声明似乎是 docs 中的标准模式,但我对 Js 和 React 还很陌生,显然做错了什么。
这是 GitHub 上的 sample project。任何帮助将不胜感激 =)
【问题讨论】:
标签: javascript reactjs unit-testing jestjs es6-promise