首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >模拟获取Jest测试引发“无效的json响应”和“未处理的承诺拒绝”错误

模拟获取Jest测试引发“无效的json响应”和“未处理的承诺拒绝”错误
EN

Stack Overflow用户
提问于 2019-08-17 00:55:07
回答 1查看 5.3K关注 0票数 2

我正在尝试对我的一些redux-saga生成器进行单元测试,并得到了一些错误,我不知道如何解决。我使用的是create-react-app,所以我的测试套件是Jest和酵素。

一个基本的例子:

设置: src/setupTests.js

代码语言:javascript
复制
import 'jest-enzyme'
import { configure } from 'enzyme'
import Adapter from 'enzyme-adapter-react-16'

global.fetch = require('jest-fetch-mock')

configure({
    adapter: new Adapter(),
    automock: false,
    collectCoverageFrom: [
        '<rootDir>/src/**/*.js',
        '!<rootDir>/src/**/*.stories.js',
        '!<rootDir>/node_modules/',
        '!<rootDir>/src/index.js',
    ],
    coverageThreshold: {
        global: {
            branches: 90,
            functions: 90,
            lines: 90,
            statements: 90,
        },
    },
    verbose: true,
})

传奇: src/store/sagas/api-saga.js

代码语言:javascript
复制
import { takeEvery, put } from 'redux-saga/effects'

import {
    API_ERRORED,
    DATA_LOADED,
    DATA_REQUESTED,
} from '../constants/action-types'

export function* workerSaga() {
    try {
        const payload =
            yield fetch('https://jsonplaceholder.typicode.com/posts')
                .then(response => response.json())
        yield put({
            type: DATA_LOADED,
            payload,
        })
    } catch (e) {
        yield put({
            type: API_ERRORED,
            payload: false,
        })
    }
}

export default function* watcherSaga() {
    yield takeEvery(
        DATA_REQUESTED,
        workerSaga,
    )
}

佐贺测试: src/store/sagas/api-saga.test.js

代码语言:javascript
复制
import { put, takeEvery } from 'redux-saga/effects'
import watcherSaga, { workerSaga } from './api-saga'

import {
    API_ERRORED,
    DATA_LOADED,
    DATA_REQUESTED,
} from '../constants/action-types'

describe('saga workers', () => {
    test('should dispatch action "DATA_LOADED" with result from fetch API',
        () => {
            const articles = 'Some content'
            const mockResponse = {
                articles,
            }
            const generator = workerSaga()

            generator.next()

            expect(generator.next(mockResponse).value)
                .toEqual(
                    put({
                        type: DATA_LOADED,
                        payload: {
                            articles,
                        },
                    })
                )

            expect(generator.next().done).toBeTruthy()
        })
})

我收到的错误:

代码语言:javascript
复制
(node:2009) UnhandledPromiseRejectionWarning: FetchError: invalid json response body at undefined reason: Unexpected end of JSON input
(node:2009) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 2)
(node:2009) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
(node:2009) UnhandledPromiseRejectionWarning: FetchError: invalid json response body at undefined reason: Unexpected end of JSON input
(node:2009) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 4)

我认为引入jest-fetch-mock将有助于解决其中的一些问题,但似乎并非如此。测试通过了,但这些错误仍然存在。

我遗漏了什么?

版本

redux@4.0.4

redux-saga@1.0.5

酶@3.10.0

jest@24.7.1

EN

回答 1

Stack Overflow用户

发布于 2019-08-20 19:53:21

您需要设置jest-fetch-mock来返回一个值:

类似于:

代码语言:javascript
复制
describe('saga workers', () => {
    test('should dispatch action "DATA_LOADED" with result from fetch API',
        () => {
            const articles = 'Some content'
            const mockResponse = {
                articles,
            }
            // configure the mockResponse here:
            fetch.mockResponse(mockResponse);
            const generator = workerSaga()

            generator.next()

            expect(generator.next().value)
                .toEqual(
                    put({
                        type: DATA_LOADED,
                        payload: {
                            articles,
                        },
                    })
                )

            expect(generator.next().done).toBeTruthy()
        })
})

请参阅https://github.com/jefflau/jest-fetch-mock#api

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57532528

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档