我在课堂上有以下方法:
import axios from 'axios'
public async getData() {
const resp = await axios.get(Endpoints.DATA.URL)
return resp.data
}
Run Code Online (Sandbox Code Playgroud)
然后,我试图建立一个Jest测试来做到这一点:
jest.mock('axios')
it('make api call to get data', () => {
component.getData()
expect(axios.get).toHaveBeenCalledWith(Endpoints.DATA.URL)
})
Run Code Online (Sandbox Code Playgroud)
问题是,因为我不是嘲笑的返回值,那么它给出了一个错误resp.data,因为我打电话data上null或undefined对象。我花了至少2个小时的时间尝试各种方法来使此工作正常进行,但是我找不到能够模拟axios.get一些返回值的方法。
Jest的文档使用JavaScript,因此他们给出了这个示例,axios.get.mockResolvedValue(resp)但我不能调用,mockResolvedValue因为axios.getTypeScript 中不存在该方法。
另外,如果您知道除Jest之外的React的其他优秀测试库,这些库很容易为TypeScript做到这一点,请随时共享。