{"size": 1603, "ext": "js", "max_stars_repo_path": "Chapter12/chapter12_2/__tests__/actions/users.test.js", "max_stars_repo_name": "robert0714/Learning-Redux", "max_stars_repo_stars_event_min_datetime": "2017-09-12T09:21:16.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T01:20:45.000Z", "max_issues_repo_path": "Chapter12/chapter12_2/__tests__/actions/users.test.js", "max_issues_repo_name": "robert0714/Learning-Redux", "max_issues_repo_issues_event_min_datetime": "2018-01-02T17:10:03.000Z", "max_issues_repo_issues_event_max_datetime": "2019-03-01T10:59:56.000Z", "max_forks_repo_path": "Chapter12/chapter12_2/__tests__/actions/users.test.js", "max_forks_repo_name": "robert0714/Learning-Redux", "max_forks_repo_forks_event_min_datetime": "2017-09-04T20:54:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-20T09:21:37.000Z"}
{"max_stars_count": 43, "max_issues_count": 4, "max_forks_count": 27, "avg_line_length": 25.046875, "max_line_length": 74, "alphanum_fraction": 0.6444167187}
import configureMockStore from 'redux-mock-store'
import thunk from 'redux-thunk'
import nock from 'nock'

import { fetchUser } from '../../src/actions'
import * as actionTypes from '../../src/actionTypes'

const middlewares = [ thunk ]
const mockStore = configureMockStore(middlewares)
let store

beforeEach(() => {
  store = mockStore({ users: [] })
})

afterEach(() => {
  nock.cleanAll()
})

describe('fetching user', () => {
  test('dispatches FETCH_USER_SUCCESS when fetching succeeds', () => {
    const username = 'dan'
    const realname = 'Daniel Bugl'
    const userObj = { username, realname }

    nock('http://localhost:8080/')
      .get(`/api/users/${username}`)
      .reply(200, userObj)

    const expectedActions = [
      { type: actionTypes.FETCH_USER_REQUEST },
      { type: actionTypes.FETCH_USER_SUCCESS, result: userObj }
    ]

    expect.assertions(1)

    return store.dispatch(fetchUser(username))
      .then(() =>
        expect(store.getActions()).toEqual(expectedActions)
      )
  })

  test('dispatches FETCH_USER_FAILURE when fetching fails', () => {
    const username = 'nonexistant'
    const errorMsg = 'user not found'

    nock('http://localhost:8080/')
      .get(`/api/users/${username}`)
      .reply(404, { error: errorMsg })

    const expectedActions = [
      { type: actionTypes.FETCH_USER_REQUEST },
      { type: actionTypes.FETCH_USER_FAILURE, error: new Error(errorMsg) }
    ]

    expect.assertions(1)

    return store.dispatch(fetchUser(username))
      .catch(() =>
        expect(store.getActions()).toEqual(expectedActions)
      )
  })
})
