React native 在jest中使用async/await调用api总是获得状态200
我在我的React native 在jest中使用async/await调用api总是获得状态200,react-native,jestjs,React Native,Jestjs,我在我的App.test.js文件中调用一个api来测试api: 我已经安装了jest fetch mock 以下是我的声明: "devDependencies": { "babel-preset-react-native-stage-0": "^1.0.1", "eslint-config-rallycoding": "^3.2.0", "jest": "^23.1.0", "jest-fetch-mock": "^1.6.6", "jest-rea
App.test.js
文件中调用一个api来测试api:
我已经安装了jest fetch mock
以下是我的声明:
"devDependencies": {
"babel-preset-react-native-stage-0": "^1.0.1",
"eslint-config-rallycoding": "^3.2.0",
"jest": "^23.1.0",
"jest-fetch-mock": "^1.6.6",
"jest-react-native": "^18.0.0",
"react-test-renderer": "16.3.1"
},
App.test.js
:
describe('Test API', () => {
it('ack', async () => {
const response = await fetch('https://obscure-reaches-65656.herokuapp.com/api/drivers?city=TaipeiWest&lng=121.514163&lat=25.049447');
expect(response).toBeDefined();
console.log(response);
});
});
我发现如果我使用无用的apihttps://obscure-reaches-65656.herokuapp.com/api/drivers?city=&lng=121.514163&lat=25.049447
或者移除它
const response = await fetch('');
然后键入npm运行测试
我仍然得到状态是200
这是console.log
Response {
type: 'default',
status: 200,
ok: true,
statusText: 'OK',
headers: Headers { map: { 'content-type': 'text/plain;charset=UTF-8' } },
url: '',
_bodyInit: '',
_bodyText: '' }
为什么异步/awiat不工作?我想我会得到422的状态。
任何帮助都将不胜感激。Than提前发出。在使用async/await时,您总是会得到响应,因为您没有等待请求的承诺。这是因为在description
方法中没有正确使用async
仔细看一看
要使代码正常工作,请将async添加到description
内部箭头函数中,如下所示:
describe('Test API', async () => {
it('ack', async () => {
const response = await fetch('https://obscure-reaches-65656.herokuapp.com/api/drivers?city=TaipeiWest&lng=121.514163&lat=25.049447');
expect(response).toBeDefined();
console.log(response);
});
});
如果仍然得到相同的响应,请将wait
添加到it
(如果响应是承诺,则应该没有问题):
您还可以查看并了解如何处理异步测试。我使用wait it('ack',async()=>{
这是一个承诺,尽管api为空,但返回的状态仍然是200。还不能理解。感谢提供了大量有用的信息,我将研究它。
await it('ack', async () => {