+
quantity: {this.state.quantity}
{this.state.isSaved && }
@@ -65,7 +71,7 @@ const Home = ({ history }) => {
return (
Home
-
+
)
}
@@ -79,7 +85,7 @@ const PageUsingLocationState = () => {
useEffect(() => {
if (location.state) setTitle(location.state.title)
- },[location.state])
+ }, [location.state])
return
{title}
}
@@ -88,19 +94,19 @@ export const history = createBrowserHistory()
export const MyAppWithRouting = () => {
return (
-
+
-
+
-
@@ -112,12 +118,12 @@ export const MyAppWithBrowserRouting = () => {
return (
-
+
@@ -134,18 +140,18 @@ const remove = () => dispatch => dispatch({ type: ACTION_TYPES.REMOVE })
function reducer(state = { products: 10 }, action) {
switch (action.type) {
- case ACTION_TYPES.ADD:
- return {
- products: state.products + 1,
- }
-
- case ACTION_TYPES.REMOVE:
- return {
- products: state.products - 1,
- }
-
- default:
- return state
+ case ACTION_TYPES.ADD:
+ return {
+ products: state.products + 1,
+ }
+
+ case ACTION_TYPES.REMOVE:
+ return {
+ products: state.products - 1,
+ }
+
+ default:
+ return state
}
}
@@ -156,8 +162,8 @@ const Cart = () => {
return (
{products}
-
-
+
+
)
}
@@ -165,7 +171,7 @@ const Cart = () => {
export const MyAppWithStore = () => {
return (
@@ -252,7 +258,7 @@ export const MyComponentWithLogin = () => {
return (
Logged in as {username}
-
+
)
}
@@ -302,15 +308,42 @@ export const MyComponentWithFeedback = () => {
})
const response = await fetch(request)
- if(!response) return
+ if (!response) return
const { name } = await response.json()
setFeedback(name)
}
return (
-
+
{feedback}
)
}
+
+export const GreetingComponent = () => {
+ const [name, setName] = useState('')
+
+ useEffect(() => {
+ async function fetchData() {
+ await fetch(
+ new Request('my-host/request1', {
+ method: 'POST',
+ body: JSON.stringify({ id: 1 }),
+ }),
+ )
+
+ const response = await fetch(
+ new Request('my-host/request2', {
+ method: 'POST',
+ body: JSON.stringify({ id: 2 }),
+ }),
+ )
+ const data = await response.json()
+ setName(data?.name)
+ }
+ fetchData()
+ }, [])
+
+ return Hi {name}!
+}
diff --git a/tests/helpers.js b/tests/helpers.ts
similarity index 99%
rename from tests/helpers.js
rename to tests/helpers.ts
index a8573f5..3732c99 100644
--- a/tests/helpers.js
+++ b/tests/helpers.ts
@@ -8,4 +8,4 @@ export const refreshProductsList = container => {
export const getTableRowsText = container => {
const { getAllByRole } = within(container)
return getAllByRole('row').map(row => row.textContent)
-}
\ No newline at end of file
+}
diff --git a/tests/atPath.test.js b/tests/lib/atPath.test.ts
similarity index 72%
rename from tests/atPath.test.js
rename to tests/lib/atPath.test.ts
index 0f34106..b9c3e3a 100644
--- a/tests/atPath.test.js
+++ b/tests/lib/atPath.test.ts
@@ -1,12 +1,21 @@
-import { wrap, configure } from '../src'
+import { wrap, configure } from '../../src'
import { render, fireEvent, screen } from '@testing-library/react'
+import { vi, expect, beforeAll, afterAll, it } from 'vitest'
import {
MyAppWithRouting,
MyComponent,
history,
myFakeModule,
-} from './components.mock'
+} from '../components.mock'
+
+const originalWarn = window.console.warn
+
+beforeAll(() => (window.console.warn = vi.fn()))
+
+afterAll(() => {
+ window.console.warn = originalWarn
+})
configure({ mount: render })
@@ -20,11 +29,11 @@ it('should render an app without routing with specific url', () => {
wrap(MyComponent).atPath('/?query=query').mount()
expect(screen.getByText('Foo')).toBeInTheDocument()
- expect(window.location.href).toBe('http://localhost/?query=query')
+ expect(window.location.href).toBe('http://localhost:3000/?query=query')
})
it('should render an app with routing given an specific path using changeRoute', () => {
- const functionCalledByHomeRoute = jest.spyOn(myFakeModule, 'myFakeFunction')
+ const functionCalledByHomeRoute = vi.spyOn(myFakeModule, 'myFakeFunction')
configure({ changeRoute: history.push })
const { container } = wrap(MyAppWithRouting).atPath('/categories').mount()
@@ -33,7 +42,7 @@ it('should render an app with routing given an specific path using changeRoute',
})
it('should render an app with routing given an specific path using history', () => {
- const functionCalledByHomeRoute = jest.spyOn(myFakeModule, 'myFakeFunction')
+ const functionCalledByHomeRoute = vi.spyOn(myFakeModule, 'myFakeFunction')
configure({ history })
const { container } = wrap(MyAppWithRouting).atPath('/categories').mount()
@@ -42,7 +51,7 @@ it('should render an app with routing given an specific path using history', ()
})
it('should warn that history config is deprecated', () => {
- const warn = jest.spyOn(console, 'warn')
+ const warn = vi.spyOn(console, 'warn')
configure({ history })
wrap(MyAppWithRouting).atPath('/categories').mount()
@@ -63,9 +72,11 @@ it('should render an app with a routing logic between pages', () => {
expect(container).toHaveTextContent('Categories')
})
-it('should render an app with a location state', async () =>{
+it('should render an app with a location state', async () => {
configure({ history })
- wrap(MyAppWithRouting).atPath('/page-using-location-state', {title: "title"}).mount()
+ wrap(MyAppWithRouting)
+ .atPath('/page-using-location-state', { title: 'title' })
+ .mount()
expect(await screen.findByText('title')).toBeInTheDocument()
-})
+})
diff --git a/tests/debugRequests.test.js b/tests/lib/debugRequests.test.ts
similarity index 71%
rename from tests/debugRequests.test.js
rename to tests/lib/debugRequests.test.ts
index b2ea716..11c074a 100644
--- a/tests/debugRequests.test.js
+++ b/tests/lib/debugRequests.test.ts
@@ -1,51 +1,39 @@
-import React, { useEffect, useState } from 'react'
-import { render, cleanup, screen, fireEvent } from '@testing-library/react'
-import { wrap, configure } from '../src/index'
-import { MyComponentWithFeedback } from './components.mock'
-
-configure({ defaultHost: 'my-host', mount: render })
+import { cleanup, fireEvent, render, screen } from '@testing-library/react'
+import { configure, wrap } from '../../src/index'
+import { GreetingComponent, MyComponentWithFeedback } from '../components.mock'
+import {
+ afterAll,
+ afterEach,
+ beforeAll,
+ describe,
+ expect,
+ it,
+ vi,
+} from 'vitest'
+
+const originalWarn = window.console.warn
+
+beforeAll(() => (window.console.warn = vi.fn()))
afterEach(() => {
cleanup()
process.env.npm_config_debugRequests = undefined
- console.warn.mockRestore()
})
-const GreetingComponent = () => {
- const [name, setName] = useState('')
-
- useEffect(() => {
- async function fetchData() {
- await fetch(
- new Request('my-host/request1', {
- method: 'POST',
- body: JSON.stringify({ id: 1 }),
- }),
- )
-
- const response = await fetch(
- new Request('my-host/request2', {
- method: 'POST',
- body: JSON.stringify({ id: 2 }),
- }),
- )
- const data = await response.json()
- setName(data?.name)
- }
- fetchData()
- }, [])
-
- return Hi {name}!
-}
+afterAll(() => {
+ window.console.warn = originalWarn
+})
+
+configure({ defaultHost: 'my-host', mount: render })
it('should warn about the code making a request that has not being mocked', async () => {
- const consoleWarn = jest.spyOn(console, 'warn').mockImplementation()
+ const consoleWarn = vi.spyOn(console, 'warn')
wrap(GreetingComponent)
.withNetwork({
path: '/request2',
host: 'my-host',
- method: 'post',
+ method: 'POST',
requestBody: { id: 2 },
responseBody: { name: 'Sam' },
})
@@ -69,13 +57,13 @@ it('should warn about the code making a request that has not being mocked', asyn
})
it('should warn about the code making a request that has not being mocked enough times', async () => {
- const consoleWarn = jest.spyOn(console, 'warn').mockImplementation()
+ const consoleWarn = vi.spyOn(console, 'warn')
configure({ mount: render })
wrap(MyComponentWithFeedback)
.withNetwork({
host: 'my-host',
path: '/path/to/save/',
- method: 'post',
+ method: 'POST',
multipleResponses: [{ responseBody: { name: 'Sam' } }],
})
.debugRequests()
@@ -88,14 +76,14 @@ it('should warn about the code making a request that has not being mocked enough
expect(consoleWarn).toHaveBeenCalledWith(
expect.stringContaining(
- '🌯 Wrapito: Missing response in the multipleResponses array for path /path/to/save/ and method post.',
+ '🌯 Wrapito: Missing response in the multipleResponses array for path /path/to/save/ and method POST.',
),
)
})
describe('when no using withNetwork builder', () => {
it('should warn about all the request being done by the production code', async () => {
- const consoleWarn = jest.spyOn(console, 'warn').mockImplementation()
+ const consoleWarn = vi.spyOn(console, 'warn')
wrap(GreetingComponent).debugRequests().mount()
@@ -126,13 +114,13 @@ describe('when no using withNetwork builder', () => {
})
it('should not warn if the debugRequests feature is not used', async () => {
- const consoleWarn = jest.spyOn(console, 'warn').mockImplementation()
+ const consoleWarn = vi.spyOn(console, 'warn')
wrap(GreetingComponent)
.withNetwork({
path: '/request2',
host: 'my-host',
- method: 'post',
+ method: 'POST',
requestBody: { id: 2 },
responseBody: { name: 'Sam' },
})
@@ -146,21 +134,21 @@ it('should not warn if the debugRequests feature is not used', async () => {
})
it('should not warn if all the requests are being mocked', async () => {
- const consoleWarn = jest.spyOn(console, 'warn').mockImplementation()
+ const consoleWarn = vi.spyOn(console, 'warn')
wrap(GreetingComponent)
.withNetwork([
{
path: '/request1',
host: 'my-host',
- method: 'post',
+ method: 'POST',
requestBody: { id: 1 },
responseBody: { name: 'Joe' },
},
{
path: '/request2',
host: 'my-host',
- method: 'post',
+ method: 'POST',
requestBody: { id: 2 },
responseBody: { name: 'Sam' },
},
@@ -176,7 +164,37 @@ it('should not warn if all the requests are being mocked', async () => {
})
it('should warn about not fetched requests when --debugRequests param is used', async () => {
- const consoleWarn = jest.spyOn(console, 'warn').mockImplementation()
+ const consoleWarn = vi.spyOn(console, 'warn')
+ process.env.npm_config_debugRequests = 'true'
+
+ wrap(GreetingComponent)
+ .withNetwork({
+ path: '/request2',
+ host: 'my-host',
+ method: 'POST',
+ requestBody: { id: 2 },
+ responseBody: { name: 'Sam' },
+ })
+ .mount()
+
+ await screen.findByText('Hi Sam!')
+
+ expect(consoleWarn).toHaveBeenCalledWith(
+ expect.stringContaining('cannot find any mock matching:'),
+ )
+ expect(consoleWarn).toHaveBeenCalledWith(
+ expect.stringContaining('URL: my-host/request1'),
+ )
+ expect(consoleWarn).toHaveBeenCalledWith(
+ expect.stringContaining('METHOD: post'),
+ )
+ expect(consoleWarn).toHaveBeenCalledWith(
+ expect.stringContaining('REQUEST BODY: {"id":1}'),
+ )
+})
+
+it('should warn about not fetched requests when --debugRequests param is used with method in lowerCase', async () => {
+ const consoleWarn = vi.spyOn(console, 'warn')
process.env.npm_config_debugRequests = 'true'
wrap(GreetingComponent)
diff --git a/tests/extend.test.js b/tests/lib/extend.test.ts
similarity index 84%
rename from tests/extend.test.js
rename to tests/lib/extend.test.ts
index cf8c9df..c685be0 100644
--- a/tests/extend.test.js
+++ b/tests/lib/extend.test.ts
@@ -1,20 +1,21 @@
import { render, screen, fireEvent } from '@testing-library/react'
-import { wrap, configure } from '../src/index'
+import { vi, it, expect } from 'vitest'
+import { wrap, configure } from '../../src/index'
-import { MyComponentWithLogin, MyComponent } from './components.mock'
+import { MyComponentWithLogin } from '../components.mock'
it('should extend wrapito', async () => {
- const otherCustomExtension = jest.fn()
+ const otherCustomExtension = vi.fn()
const customArgs = { foo: 'bar' }
configure({
mount: render,
extend: {
- withLogin: ({ addResponses }, username) =>
+ withLogin: ({ addResponses }, username: string) =>
addResponses([
{
path: '/path/to/login/',
host: 'my-host',
- method: 'post',
+ method: 'POST',
responseBody: username,
},
]),
@@ -39,7 +40,7 @@ it('should be compatible with withNetwork', async () => {
{
path: '/path/to/login/',
host: 'my-host',
- method: 'post',
+ method: 'POST',
responseBody: username,
},
]),
@@ -51,7 +52,7 @@ it('should be compatible with withNetwork', async () => {
{
path: '/path/to/logout/',
host: 'my-host',
- method: 'post',
+ method: 'POST',
responseBody: 'John Doe',
},
])
@@ -72,7 +73,7 @@ it('should be composable', async () => {
{
path: '/path/to/login/',
host: 'my-host',
- method: 'post',
+ method: 'POST',
responseBody: username,
},
]),
@@ -83,7 +84,7 @@ it('should be composable', async () => {
{
path: '/path/to/logout/',
host: 'my-host',
- method: 'post',
+ method: 'POST',
responseBody: 'John Doe',
},
])
@@ -95,5 +96,3 @@ it('should be composable', async () => {
expect(await screen.findByText('Logged out as John Doe')).toBeInTheDocument()
})
-
-
diff --git a/tests/withNetwork.test.js b/tests/lib/withNetwork.test.ts
similarity index 82%
rename from tests/withNetwork.test.js
rename to tests/lib/withNetwork.test.ts
index 2f8ad2b..1c3258b 100644
--- a/tests/withNetwork.test.js
+++ b/tests/lib/withNetwork.test.ts
@@ -1,13 +1,13 @@
-import React from 'react'
import { render, screen, fireEvent } from '@testing-library/react'
-import { wrap, configure } from '../src/index'
+import { wrap, configure } from '../../src/index'
+import { vi, it, expect } from 'vitest'
import {
MyComponentWithNetwork,
MyComponentWithPost,
MyComponentWithFeedback,
MyComponentMakingHttpCallsWithQueryParams,
-} from './components.mock'
+} from '../components.mock'
it('should have network by default', async () => {
configure({ mount: render })
@@ -17,7 +17,7 @@ it('should have network by default', async () => {
})
it('should have network with an array of requests', async () => {
- jest.spyOn(console, 'warn')
+ vi.spyOn(console, 'warn')
configure({ mount: render })
wrap(MyComponentWithNetwork)
.withNetwork([
@@ -39,7 +39,7 @@ it('should have network without responses', async () => {
it('should resolve a request with delay after the specified time', async () => {
configure({ mount: render })
- jest.useFakeTimers()
+ vi.useFakeTimers()
wrap(MyComponentWithNetwork)
.withNetwork([
{
@@ -57,17 +57,17 @@ it('should resolve a request with delay after the specified time', async () => {
.mount()
await screen.findByText('MyComponentWithNetwork')
- jest.advanceTimersByTime(200)
+ vi.advanceTimersByTime(200)
await screen.findByText('SUCCESS')
expect(screen.getByText('SUCCESS')).toBeInTheDocument()
expect(screen.queryByText('15')).not.toBeInTheDocument()
- jest.advanceTimersByTime(500)
+ vi.advanceTimersByTime(500)
await screen.findByText('15')
expect(screen.getByText('15')).toBeInTheDocument()
- jest.useRealTimers()
+ vi.useRealTimers()
})
it('should resolve all the responses waiting for an unrelated text', async () => {
@@ -100,7 +100,7 @@ it('should match a request regardless the body order', async () => {
{
path: '/path/to/login/',
host: 'my-host',
- method: 'post',
+ method: 'POST',
requestBody: {
foo: 'foo',
bar: 'bar',
@@ -123,7 +123,7 @@ it('should mock multiple POST responses', async () => {
.withNetwork({
host: 'my-host',
path: '/path/to/save/',
- method: 'post',
+ method: 'POST',
multipleResponses: [
{ responseBody: { name: 'Fran Perea' } },
{ responseBody: { name: 'El que lo lea' } },
@@ -193,11 +193,11 @@ it('should handle fetch deafult requests when a string is passed', async () => {
const MyComponent = () => null
configure({ mount: render })
- wrap(MyComponent).withNetwork([
- { path: '/foo/bar', responseBody: { foo: 'bar'} }
- ]).mount()
+ wrap(MyComponent)
+ .withNetwork([{ path: '/foo/bar', responseBody: { foo: 'bar' } }])
+ .mount()
- const response = await fetch('/foo/bar').then((response) => response.json())
+ const response = await fetch('/foo/bar').then(response => response.json())
expect(response).toEqual({ foo: 'bar' })
})
@@ -206,11 +206,33 @@ it('should handle fetch requests with option when a string is passed', async ()
const MyComponent = () => null
configure({ mount: render })
- wrap(MyComponent).withNetwork([
- { path: '/foo/bar', method: 'POST', responseBody: { foo: 'bar'} }
- ]).mount()
+ wrap(MyComponent)
+ .withNetwork([
+ { path: '/foo/bar', method: 'POST', responseBody: { foo: 'bar' } },
+ ])
+ .mount()
- const response = await fetch('/foo/bar', { method: 'POST' }).then((response) => response.json())
+ const response = await fetch('/foo/bar', { method: 'POST' }).then(response =>
+ response.json(),
+ )
expect(response).toEqual({ foo: 'bar' })
})
+
+it('should return an spy compatible with expect API', async () => {
+ configure({ mount: render })
+
+ wrap(MyComponentWithNetwork)
+ .withNetwork([
+ { path: 'my-host/path/', method: 'POST', responseBody: { foo: 'bar' } },
+ { path: 'my-host/path/with/response/', responseBody: { foo: 'bar' } },
+ ])
+ .mount()
+
+ expect(global.fetch).toHaveBeenLastCalledWith(
+ expect.objectContaining({
+ method: 'GET',
+ url: expect.stringContaining('my-host/path/with/response/'),
+ }),
+ )
+})
diff --git a/tests/wrap.test.js b/tests/lib/wrap.test.ts
similarity index 83%
rename from tests/wrap.test.js
rename to tests/lib/wrap.test.ts
index b21b6d0..8047fb2 100644
--- a/tests/wrap.test.js
+++ b/tests/lib/wrap.test.ts
@@ -1,15 +1,16 @@
import { render, cleanup } from '@testing-library/react'
-import { wrap, configure } from '../src/index'
-import { getConfig } from '../src/config'
+import { wrap, configure } from '../../src/index'
+import { getConfig } from '../../src/config'
import {
MyComponent,
MyComponentWithProps,
MyComponentWithPortal,
-} from './components.mock'
+} from '../components.mock'
+import { it, expect, afterEach } from 'vitest'
const portalRootId = 'portal-root-id'
-const removePortals = portalRootId => {
+const removePortals = (portalRootId: string) => {
const portal = document.getElementById(portalRootId)
if (!portal) {
return
@@ -25,7 +26,9 @@ function resetMocksConfig() {
removePortals(portalRootId)
}
-afterEach(resetMocksConfig)
+afterEach(() => {
+ resetMocksConfig()
+})
it('should have props', () => {
configure({ mount: render })
@@ -54,7 +57,7 @@ it('should have unique portals', () => {
wrap(MyComponentWithPortal).withProps(props).mount()
wrap(MyComponentWithPortal).withProps(props).mount()
- expect(document.querySelectorAll(`#${ portalRootId }`)).toHaveLength(1)
+ expect(document.querySelectorAll(`#${portalRootId}`)).toHaveLength(1)
})
it('should use the default mount', () => {
diff --git a/tests/assertions/toHaveBeenFetched.test.js b/tests/matchers/toHaveBeenFetched.test.ts
similarity index 83%
rename from tests/assertions/toHaveBeenFetched.test.js
rename to tests/matchers/toHaveBeenFetched.test.ts
index 1034441..6ace8b3 100644
--- a/tests/assertions/toHaveBeenFetched.test.js
+++ b/tests/matchers/toHaveBeenFetched.test.ts
@@ -1,6 +1,6 @@
-import { assertions, configure } from '../../src'
-
-expect.extend(assertions)
+import { configure } from '../../src'
+import { matchers } from '../../src/matchers'
+import { describe, it, expect } from 'vitest'
describe('toHaveBeenFetched', () => {
it('should check that the path has been called', async () => {
@@ -8,7 +8,7 @@ describe('toHaveBeenFetched', () => {
const expectedPath = '/some/path/'
await fetch(new Request(path))
- const { message } = await assertions.toHaveBeenFetched(expectedPath)
+ const { message } = matchers.toHaveBeenFetched(expectedPath)
expect(message()).toBe('🌯 Wrapito: /some/path/ is called')
expect(expectedPath).toHaveBeenFetched()
@@ -19,7 +19,7 @@ describe('toHaveBeenFetched', () => {
const expectedPath = '/some/unknown'
await fetch(new Request(path))
- const { message } = await assertions.toHaveBeenFetched(expectedPath)
+ const { message } = matchers.toHaveBeenFetched(expectedPath)
expect(message()).toBe("🌯 Wrapito: /some/unknown ain't got called")
expect(expectedPath).not.toHaveBeenFetched()
@@ -30,7 +30,7 @@ describe('toHaveBeenFetched', () => {
const expectedPath = '/some/path/'
await fetch(path)
- const { message } = await assertions.toHaveBeenFetched(expectedPath)
+ const { message } = matchers.toHaveBeenFetched(expectedPath)
expect(message()).toBe('🌯 Wrapito: /some/path/ is called')
expect(expectedPath).toHaveBeenFetched()
@@ -44,7 +44,7 @@ describe('toHaveBeenFetched', () => {
defaultHost: 'https://some-domain.com',
})
await fetch(new Request(path))
- const { message } = await assertions.toHaveBeenFetched(expectedPath, {
+ const { message } = matchers.toHaveBeenFetched(expectedPath, {
host,
})
@@ -63,7 +63,7 @@ describe('toHaveBeenFetched', () => {
defaultHost: '/some-domain.com',
})
await fetch(new Request(path))
- const { message } = await assertions.toHaveBeenFetched(expectedPath, {
+ const { message } = matchers.toHaveBeenFetched(expectedPath, {
host,
})
@@ -82,7 +82,7 @@ describe('toHaveBeenFetched', () => {
defaultHost: 'https://some-domain.com',
})
await fetch(new Request(path))
- const { message } = await assertions.toHaveBeenFetched(expectedPath, {
+ const { message } = matchers.toHaveBeenFetched(expectedPath, {
host,
})
diff --git a/tests/assertions/toHaveBeenFetchedTimes.test.js b/tests/matchers/toHaveBeenFetchedTimes.test.ts
similarity index 92%
rename from tests/assertions/toHaveBeenFetchedTimes.test.js
rename to tests/matchers/toHaveBeenFetchedTimes.test.ts
index 4d55988..4d556d7 100644
--- a/tests/assertions/toHaveBeenFetchedTimes.test.js
+++ b/tests/matchers/toHaveBeenFetchedTimes.test.ts
@@ -1,6 +1,6 @@
-import { assertions, configure } from '../../src'
-
-expect.extend(assertions)
+import { configure } from '../../src'
+import { matchers } from '../../src/matchers'
+import { describe, it, expect } from 'vitest'
describe('toHaveBeenFetchedTimes', () => {
it('should count how many times an url is called', async () => {
@@ -75,7 +75,7 @@ describe('toHaveBeenFetchedTimes', () => {
const expectedPath = '/some/path/'
await fetch(new Request(path))
- const { message } = await assertions.toHaveBeenFetchedTimes(expectedPath, 2)
+ const { message } = matchers.toHaveBeenFetchedTimes(expectedPath, 2)
expect(message()).toBe(
'🌯 Wrapito: /some/path/ is called 1 times, you expected 2 times',
diff --git a/tests/assertions/toHaveBeenFetchedWith.test.js b/tests/matchers/toHaveBeenFetchedWith.test.ts
similarity index 82%
rename from tests/assertions/toHaveBeenFetchedWith.test.js
rename to tests/matchers/toHaveBeenFetchedWith.test.ts
index f41fada..d2b1cbc 100644
--- a/tests/assertions/toHaveBeenFetchedWith.test.js
+++ b/tests/matchers/toHaveBeenFetchedWith.test.ts
@@ -1,19 +1,21 @@
-import { assertions } from '../../src'
+import '../../vitest.d.ts'
+import { matchers } from '../../src/matchers'
+import { describe, it, expect } from 'vitest'
import { diff } from 'jest-diff'
-expect.extend(assertions)
+expect.extend(matchers)
describe('toHaveBeenFetchedWith', () => {
it('should check that the path has been called', async () => {
const path = '//some-domain.com/some/path/'
const expectedPath = '/some/path/'
const body = {
- method: 'POST',
+ method: 'POST' as const,
body: JSON.stringify({ name: 'some name' }),
}
await fetch(new Request(path, body))
- await assertions.toHaveBeenFetchedWith(expectedPath, body)
+ matchers.toHaveBeenFetchedWith(expectedPath, body)
expect(expectedPath).toHaveBeenFetchedWith({ body: { name: 'some name' } })
})
@@ -23,9 +25,9 @@ describe('toHaveBeenFetchedWith', () => {
const expectedPath = '/some/unknown'
await fetch(new Request(path))
- const { message } = await assertions.toHaveBeenFetchedWith(expectedPath)
+ const { message } = matchers.toHaveBeenFetchedWith(expectedPath)
- expect(message()).toBe('🌯 Wrapito: /some/unknown ain\'t got called')
+ expect(message()).toBe("🌯 Wrapito: /some/unknown ain't got called")
expect(expectedPath).not.toHaveBeenFetchedWith()
})
@@ -34,7 +36,7 @@ describe('toHaveBeenFetchedWith', () => {
const path = '//some-domain.com/some/path/'
await fetch(new Request(path))
- const { message, pass } = await assertions.toHaveBeenFetchedWith(path)
+ const { message, pass } = matchers.toHaveBeenFetchedWith(path)
expect(message()).toBe('🌯 Wrapito: Unable to find body.')
expect(pass).toBe(false)
@@ -48,13 +50,13 @@ describe('toHaveBeenFetchedWith', () => {
})
await fetch(request)
- const { message } = await assertions.toHaveBeenFetchedWith(path, {
+ const { message } = matchers.toHaveBeenFetchedWith(path, {
body: {
name: 'some name',
},
})
- expect(message()).toBeUndefined()
+ expect(message()).toBe('Test passing')
expect(path).toHaveBeenFetchedWith({
body: {
name: 'some name',
@@ -67,19 +69,22 @@ describe('toHaveBeenFetchedWith', () => {
const request = new Request(path, {
method: 'POST',
body: JSON.stringify({ name: 'some name' }),
+ //@ts-ignore
_bodyInit: JSON.stringify({ name: 'some name' }),
})
await fetch(request)
+
+ //@ts-ignore
fetch.mock.calls[0][0].json()
- const { message } = await assertions.toHaveBeenFetchedWith(path, {
+ const { message } = matchers.toHaveBeenFetchedWith(path, {
body: {
name: 'some name',
},
})
- expect(message()).toBeUndefined()
+ expect(message()).toBe('Test passing')
expect(path).toHaveBeenFetchedWith({
body: {
name: 'some name',
@@ -120,14 +125,14 @@ describe('toHaveBeenFetchedWith', () => {
})
await fetch(request)
- const { message } = await assertions.toHaveBeenFetchedWith(path, {
+ const { message } = matchers.toHaveBeenFetchedWith(path, {
body: {
surname: 'surname',
name: 'name',
},
})
- expect(message()).toBeUndefined()
+ expect(message()).toBe('Test passing')
expect(path).toHaveBeenFetchedWith({
body: {
surname: 'surname',
@@ -146,7 +151,7 @@ describe('toHaveBeenFetchedWith', () => {
})
await fetch(request)
- const { message } = await assertions.toHaveBeenFetchedWith(path, {
+ const { message } = matchers.toHaveBeenFetchedWith(path, {
body: expectedBody,
})
@@ -166,12 +171,12 @@ ${diff(expectedBody, receivedBody)}`,
const body = { method: 'POST' }
await fetch(new Request(path, body))
- const { message } = await assertions.toHaveBeenFetchedWith(path, {
+ const { message } = matchers.toHaveBeenFetchedWith(path, {
body: {},
method: 'POST',
})
- expect(message()).toBeUndefined()
+ expect(message()).toBe('Test passing')
expect(path).toHaveBeenFetchedWith({
body: {},
method: 'POST',
@@ -207,12 +212,12 @@ ${diff(expectedBody, receivedBody)}`,
await fetch(postRequest)
await fetch(putRequest)
- const { message } = await assertions.toHaveBeenFetchedWith(path, {
+ const { message } = matchers.toHaveBeenFetchedWith(path, {
body: {},
method: 'PUT',
})
- expect(message()).toBeUndefined()
+ expect(message()).toBe('Test passing')
expect(path).toHaveBeenFetchedWith({
body: {},
method: 'PUT',
@@ -224,7 +229,7 @@ ${diff(expectedBody, receivedBody)}`,
const request = new Request(path, { method: 'PUT' })
await fetch(request)
- const { message } = await assertions.toHaveBeenFetchedWith(path, {
+ const { message } = matchers.toHaveBeenFetchedWith(path, {
method: 'POST',
})
@@ -241,11 +246,11 @@ ${diff(expectedBody, receivedBody)}`,
const request = new Request(path, { method: 'POST' })
await fetch(request)
- const { message } = await assertions.toHaveBeenFetchedWith(path, {
+ const { message } = matchers.toHaveBeenFetchedWith(path, {
body: {},
})
- expect(message()).toBeUndefined()
+ expect(message()).toBe('Test passing')
expect(path).toHaveBeenFetchedWith({ body: {} })
})
})
diff --git a/tsconfig.json b/tsconfig.json
index fe230aa..c0d6fad 100644
--- a/tsconfig.json
+++ b/tsconfig.json
@@ -1,75 +1,20 @@
{
-
- "include": ["src/**/*"],
- "exclude": ["node_modules", "tests"],
"compilerOptions": {
- /* Visit https://aka.ms/tsconfig.json to read more about this file */
-
- /* Basic Options */
- // "incremental": true, /* Enable incremental compilation */
- "target": "es5", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', 'ES2021', or 'ESNEXT'. */
- "module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */
- // "lib": [], /* Specify library files to be included in the compilation. */
- "allowJs": true, /* Allow javascript files to be compiled. */
- // "checkJs": true, /* Report errors in .js files. */
- "jsx": "react-jsx", /* Specify JSX code generation: 'preserve', 'react-native', 'react', 'react-jsx' or 'react-jsxdev'. */
- "declaration": true, /* Generates corresponding '.d.ts' file. */
- "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */
- "sourceMap": true, /* Generates corresponding '.map' file. */
- // "outFile": "./", /* Concatenate and emit output to single file. */
- "outDir": "./dist", /* Redirect output structure to the directory. */
- // "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
- // "composite": true, /* Enable project compilation */
- // "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */
- // "removeComments": true, /* Do not emit comments to output. */
- // "noEmit": true, /* Do not emit outputs. */
- // "importHelpers": true, /* Import emit helpers from 'tslib'. */
- // "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
- // "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */
-
- /* Strict Type-Checking Options */
- "strict": true, /* Enable all strict type-checking options. */
- // "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */
- // "strictNullChecks": true, /* Enable strict null checks. */
- // "strictFunctionTypes": true, /* Enable strict checking of function types. */
- // "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */
- // "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */
- // "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */
- // "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */
-
- /* Additional Checks */
- // "noUnusedLocals": true, /* Report errors on unused locals. */
- // "noUnusedParameters": true, /* Report errors on unused parameters. */
- // "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */
- // "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */
- // "noUncheckedIndexedAccess": true, /* Include 'undefined' in index signature results */
- // "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an 'override' modifier. */
- // "noPropertyAccessFromIndexSignature": true, /* Require undeclared properties from index signatures to use element accesses. */
-
- /* Module Resolution Options */
- // "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
- // "baseUrl": "./", /* Base directory to resolve non-absolute module names. */
- // "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
- // "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */
- // "typeRoots": [], /* List of folders to include type definitions from. */
- // "types": [], /* Type declaration files to be included in compilation. */
- // "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
- "esModuleInterop": true, /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
- // "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */
- // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
-
- /* Source Map Options */
- // "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */
- // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
- // "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */
- // "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */
-
- /* Experimental Options */
- // "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */
- // "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */
-
- /* Advanced Options */
- "skipLibCheck": true, /* Skip type checking of declaration files. */
- "forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */
- }
+ "target": "es2020",
+ "module": "es2020",
+ "allowSyntheticDefaultImports": true,
+ "allowJs": true,
+ "jsx": "react",
+ "declaration": true,
+ "sourceMap": true,
+ "outDir": "./dist",
+ "strict": true,
+ "skipLibCheck": true,
+ "forceConsistentCasingInFileNames": true,
+ "moduleResolution": "node",
+ "types": ["vitest/globals"],
+ "esModuleInterop": true
+ },
+ "include": ["src/**/*"],
+ "exclude": ["node_modules", "tests"]
}
diff --git a/tsup.config.ts b/tsup.config.ts
new file mode 100644
index 0000000..23b02fe
--- /dev/null
+++ b/tsup.config.ts
@@ -0,0 +1,16 @@
+import { defineConfig } from 'tsup'
+
+export default defineConfig(options => ({
+ entryPoints: {
+ index: './src/index.ts',
+ },
+ outDir: 'dist',
+ format: ['cjs', 'esm'],
+ tsconfig: './tsconfig.json',
+ clean: true,
+ dts: true,
+ minify: !options?.watch,
+ outExtension: ({ format }) => ({
+ js: format === 'cjs' ? '.js' : '.mjs',
+ }),
+}))
diff --git a/vitest.config.ts b/vitest.config.ts
new file mode 100644
index 0000000..460d709
--- /dev/null
+++ b/vitest.config.ts
@@ -0,0 +1,12 @@
+import { defineConfig } from 'vitest/config'
+
+export default defineConfig({
+ test: {
+ globals: true,
+ environment: 'jsdom',
+ setupFiles: ['./config/setup.js', './config/polyfills.js'],
+ coverage: {
+ provider: 'istanbul',
+ },
+ },
+})
diff --git a/vitest.d.ts b/vitest.d.ts
new file mode 100644
index 0000000..5933a3a
--- /dev/null
+++ b/vitest.d.ts
@@ -0,0 +1,17 @@
+import type { RequestOptions } from './src/models'
+
+interface CustomMatchers {
+ toHaveBeenFetched(options?: RequestOptions): R
+ toHaveBeenFetchedWith(options?: RequestOptions): R
+ toHaveBeenFetchedTimes(expectedLength?: number, options?: RequestOptions): R
+}
+
+declare module 'vitest' {
+ interface Assertion extends CustomMatchers {}
+ interface AsymmetricMatchersContaining extends CustomMatchers {}
+}
+
+declare module 'wrapito' {
+ const matchers: CustomMatchers
+ export = matchers
+}