React native和Jest:我如何执行使用fetch的代码?

时间:2018-01-24 20:29:20

标签: javascript react-native jasmine jest

我有一些代码可以做到这一点:

export default () => {
  return fetch('example.com');
};

此文件中没有其他代码。当我运行一个调用此函数的测试时,测试会给我这个错误:

    ReferenceError: fetch is not defined

我正在使用jest并做出本机反应。由于fetch是全局的,我不知道如何解决这个问题。

以下是我的开发依赖项:

  "devDependencies": {
    "babel-eslint": "8.0.1",
    "babel-jest": "21.2.0",
    "babel-preset-react-native": "4.0.0",
    "code-push-cli": "^2.1.0-beta",
    "eslint": "4.8.0",
    "eslint-config-prettier": "2.6.0",
    "eslint-plugin-prettier": "2.3.1",
    "eslint-plugin-react": "7.4.0",
    "jest": "21.2.1",
    "prettier": "1.7.2",
    "react-test-renderer": "16.0.0",
    "sentry-cli-binary": "^1.21.0"
  },
  "jest": {
    "preset": "react-native",
    "transformIgnorePatterns": [
      "node_modules/(?!react-native|react-navigation)/"
    ]
  }

2 个答案:

答案 0 :(得分:2)

您似乎在浏览器上运行代码,该浏览器本身不支持fetch()。为了支持这样的浏览器,您需要一个polyfill,例如isomorphic-fetch。将此库添加到依赖项中,然后将其导入到您需要使用它的任何位置:

import fetch from 'isomorphic-fetch';

答案 1 :(得分:1)

除非您真正想要fetch HTTP资源进行集成测试,否则您只需在测试中模拟fetch

应用代码

async function someFuncAsync() {
    return fetch('http://example.com');
}

测试代码

const mockResponse = (status, statusText, response) => {
        return new Response(response, {
            status: status,
            statusText: statusText,
            headers: {
                'Content-type': 'application/json'
            }
        });
    }; 

describe('foo tests', () => {

    it('mocks fetch', () => {
        window.fetch = jest
            .fn()
            .mockImplementation(async () => mockResponse(200, null, JSON.stringify({ foo: 'bar' })));

        return someFuncAsync().then(async (response) => {
            const result = await response.json();
            expect(result).toEqual({ foo: 'bar' })
        })
    })
});