Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion config/jest.config.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,5 +18,8 @@
"setupFilesAfterEnv": ["<rootDir>/config/jest.setup.js"],
"testMatch": [ "<rootDir>/tests/**/?(*.)(test).js" ],
"moduleFileExtensions": ["js", "json", "ts", "tsx"],
"reporters": [ "default", "jest-junit" ]
"reporters": [ "default", "jest-junit" ],
"moduleNameMapper": {
"axios": "axios/dist/node/axios.cjs"
}
}
36 changes: 36 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@
"@types/history": "^4.7.9",
"@types/jest": "^26.0.23",
"@types/react": "^17.0.16",
"axios": "^1.2.2",
"babel-jest": "^24.8.0",
"jest": "^27.0.4",
"jest-junit": "^6.4.0",
Expand Down
47 changes: 47 additions & 0 deletions src/mockNetwork.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,17 +5,61 @@ import { getRequestMatcher } from './requestMatcher'
declare global {
interface Window {
fetch: jest.Mock
XMLHttpRequest: jest.Mock
}
}

beforeEach(() => {
global.window.fetch = jest.fn()
global.window.XMLHttpRequest = jest.fn() as jest.MockedClass<
typeof global.window.XMLHttpRequest
>
})

afterEach(() => {
global.window.fetch.mockRestore()
global.window.XMLHttpRequest.mockRestore()
})

class XHRMock {
responses: Response[] = []
method: string = ''
url: string = ''
status: number = 200
readyState: number = 0
response: any | undefined
_onreadystatechange: () => void = () => null

constructor(responses: Response[]) {
this.responses = responses
}

open(method: string, url: string) {
this.method = method
this.url = url
}

send() {
const request = {
method: this.method,
url: this.url,
}

const responseMatchingRequest = this.responses.find(
getRequestMatcher(request),
)

this.status = responseMatchingRequest?.status || 200
this.response = responseMatchingRequest?.responseBody
this.readyState = 4
this._onreadystatechange()
}

set onreadystatechange(fn: () => void) {
this._onreadystatechange = fn
}
}

const createDefaultResponse = async () => {
const response = {
json: () => Promise.resolve(),
Expand Down Expand Up @@ -102,6 +146,9 @@ const mockNetwork = (responses: Response[] = [], debug: boolean = false) => {
const request = input
return mockFetch(responses, request, debug)
})

const XMLHttpRequest = global.window.XMLHttpRequest
XMLHttpRequest.mockImplementation(() => new XHRMock(responses))
}

const printMultipleResponsesWarning = (response: Response) => {
Expand Down
1 change: 1 addition & 0 deletions tests/components.mock.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import axios from 'axios/lib/axios'
import React, { Component, Fragment, useState, useEffect } from 'react'
import { createPortal } from 'react-dom'
import { Provider, useDispatch, useSelector } from 'react-redux'
Expand Down
49 changes: 49 additions & 0 deletions tests/withNetwork.xhr.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import React from 'react'
import axios from 'axios'
import { render, screen, fireEvent } from '@testing-library/react'
import { wrap, configure } from '../src/index'

it('should have network by default', async () => {
configure({ mount: render })
wrap(() => <div></div>).withNetwork([
{ path: '/foo/bar', responseBody: { foo: 'bar' }}
]).mount()
const mockedFn = jest.fn()
let xhr = new XMLHttpRequest()
xhr.open('GET', '/foo/bar')
xhr.onreadystatechange = mockedFn
xhr.send()

expect(xhr.response).toEqual({ foo: 'bar' })
expect(xhr.status).toEqual(200)
expect(mockedFn).toHaveBeenCalled()
})

it('should have network by default', async () => {
configure({ mount: render })
wrap(() => <div></div>).withNetwork([
{ path: '/bar/foo', responseBody: { bar: 'foo' }},
{ path: '/foo/bar', responseBody: { foo: 'bar' }},
]).mount()

const firstResponse = await axios.get('/foo/bar', { responseType: 'application/json' })
const secondResponse = await axios.get('/bar/foo', { responseType: 'application/json' })

expect(firstResponse.data).toEqual({ foo: 'bar' })
expect(secondResponse.data).toEqual({ bar: 'foo' })
})

it('should handle failed axios requests', async () => {
configure({ mount: render })
wrap(() => <div></div>).withNetwork([
{ path: '/bar/foo', responseBody: { bar: 'foo' }, status: 400},
]).mount()

try {
await axios.get('/bar/foo', { responseType: 'application/json' })
} catch (error) {
expect(error.name).toBe('AxiosError')
expect(error.message).toBe('Request failed with status code 400')
expect(error.response.data).toEqual({ bar: 'foo' })
}
})