Skip to content

Commit

Permalink
Migrate tests to testing-library (#3027)
Browse files Browse the repository at this point in the history
* test: move Box tests to testing-library

* feat: move single-target integration tests to testing-library

* chore: cut semver doc

* feat: update wrapInTestContext to allow for usage with other Backends

* refactor: use the act function provided by testing-library

* refactor: use wrapWithBackend in box.spec

* refactor: update tests to use updated wrapper functions

* refactor: move drag sequence simulations into separate module

* refactor: use wrapWithBackend in tests

* feat: add testing-library drag/drop sequences to utils

* test: migrate multi-target integ test in decorators

* test: remove enzyme

* fix: add @types/node to examples-decorators
  • Loading branch information
darthtrevino committed Feb 11, 2021
1 parent 7a89d46 commit 75b37f9
Show file tree
Hide file tree
Showing 63 changed files with 509 additions and 1,163 deletions.
509 changes: 61 additions & 448 deletions .pnp.js

Large diffs are not rendered by default.

Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file removed .yarn/cache/moo-npm-0.5.1-6281c30315-d637b67ae6.zip
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file removed .yarn/cache/raf-npm-3.4.1-c25d48d76e-567b0160be.zip
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
8 changes: 8 additions & 0 deletions .yarn/versions/a42237ad.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
releases:
react-dnd-examples-decorators: patch
react-dnd-examples-hooks: patch
react-dnd-html5-backend: patch
react-dnd-test-utils: minor

declined:
- react-dnd-documentation
2 changes: 1 addition & 1 deletion jest.config.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
module.exports = {
rootDir: __dirname,
setupFilesAfterEnv: ['<rootDir>/jest/setup-enzyme.js'],
setupFilesAfterEnv: ['<rootDir>/jest/setup-testing-library.js'],
collectCoverageFrom: [
'packages/*/src/**/*.{ts,tsx}',
'!**/__tests__/**',
Expand Down
5 changes: 0 additions & 5 deletions jest/setup-enzyme.js

This file was deleted.

1 change: 1 addition & 0 deletions jest/setup-testing-library.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
import '@testing-library/jest-dom'
2 changes: 0 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -75,10 +75,8 @@
"@types/testing-library__jest-dom": "^5",
"@typescript-eslint/eslint-plugin": "^4.15.0",
"@typescript-eslint/parser": "^4.15.0",
"@wojtekmaj/enzyme-adapter-react-17": "^0.4.1",
"alex": "^9.1.0",
"conventional-changelog-cli": "^2.1.1",
"enzyme": "^3.11.0",
"eslint": "^7.19.0",
"eslint-config-prettier": "^7.2.0",
"eslint-config-react-app": "^6.0.0",
Expand Down
4 changes: 2 additions & 2 deletions packages/backend-html5/src/HTML5BackendImpl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -649,7 +649,7 @@ export class HTML5BackendImpl implements Backend {
this.dropTargetIds = []

if (this.isDraggingNativeItem()) {
e.preventDefault();
e.preventDefault()
this.currentNativeSource?.loadDataTransfer(e.dataTransfer)
}

Expand All @@ -672,7 +672,7 @@ export class HTML5BackendImpl implements Backend {
if (this.isDraggingNativeItem()) {
this.endDragNativeItem()
} else {
this.endDragIfSourceWasRemovedFromDOM()
this.actions.endDrag()
}
}

Expand Down
3 changes: 1 addition & 2 deletions packages/examples-decorators/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -35,14 +35,13 @@
"@react-dnd/build": "workspace:packages/build",
"@testing-library/jest-dom": "^5.11.9",
"@testing-library/react": "^11.2.5",
"@types/enzyme": "^3.10.8",
"@types/faker": "^5.1.6",
"@types/jest": "^26.0.20",
"@types/lodash": "^4.14.168",
"@types/node": "^14.14.25",
"@types/react": "^17.0.1",
"@types/react-dom": "^17.0.0",
"@types/testing-library__jest-dom": "^5",
"enzyme": "^3.11.0",
"gulp": "^4.0.2",
"npm-run-all": "^4.1.5",
"react": "^17.0.1",
Expand Down
Original file line number Diff line number Diff line change
@@ -1,30 +1,16 @@
import '@testing-library/jest-dom'
import { DndProvider } from 'react-dnd'
import { HTML5Backend } from 'react-dnd-html5-backend'
import { render, screen, fireEvent, RenderResult } from '@testing-library/react'
import { render, screen, RenderResult } from '@testing-library/react'
import { Game } from '../Game'
import { Board } from '../Board'
import { OverlayType } from '../Overlay'
import {
fireDragDrop,
fireDragHover,
wrapWithBackend,
} from 'react-dnd-test-utils'

function dragAndDrop(knight: HTMLElement, space: HTMLElement) {
fireEvent.dragStart(knight)
fireEvent.dragEnter(space)
fireEvent.dragOver(space)
fireEvent.drop(space)
}

function dragHold(knight: HTMLElement, space: HTMLElement) {
fireEvent.dragStart(knight)
fireEvent.dragEnter(space)
fireEvent.dragOver(space)
}

const TestBoard = wrapWithBackend(Board)
function renderGame(game: Game): RenderResult {
return render(
<DndProvider backend={HTML5Backend}>
<Board game={game} />
</DndProvider>,
)
return render(<TestBoard game={game} />)
}

describe('The Chess Example', () => {
Expand Down Expand Up @@ -86,7 +72,7 @@ describe('The Chess Example', () => {
it('highlights legal positions when the knight is drag-held', async () => {
const knight = screen.getByText('♘')

dragHold(knight, screen.getByTestId('(1,7)'))
await fireDragHover(knight, screen.getByTestId('(1,7)'))

// Yellow cell is knight moving range
const legalMoves = screen.getAllByRole(OverlayType.PossibleMove)
Expand All @@ -102,33 +88,31 @@ describe('The Chess Example', () => {
})

// Knight initially has moving position 'index: 40 42 51' of 64 cell array
it('can move to (0,5)', () => {
it('can move to (0,5)', async () => {
const knight = screen.getByText('♘')
const targetSpace = screen.getByTestId('(0,5)')
dragAndDrop(knight, targetSpace)
await fireDragDrop(knight, targetSpace)
expect(targetSpace).toHaveTextContent('♘')
})

it('can move to space (2,5))', () => {
it('can move to space (2,5))', async () => {
const knight = screen.getByText('♘')
const targetSpace = screen.getByTestId('(2,5)')
dragAndDrop(knight, targetSpace)
await fireDragDrop(knight, targetSpace)
expect(targetSpace).toHaveTextContent('♘')
})

it('can move to space (3,6))', () => {
it('can move to space (3,6))', async () => {
const knight = screen.getByText('♘')
const targetSpace = screen.getByTestId('(3,6)')
dragAndDrop(knight, targetSpace)
await fireDragDrop(knight, targetSpace)
expect(targetSpace).toHaveTextContent('♘')
})

it('cannot move to an illegal space', () => {
it('cannot move to an illegal space', async () => {
const knight = screen.getByText('♘')
const illegalSpace = screen.getByTestId('(0,7)')

dragAndDrop(knight, illegalSpace)

await fireDragDrop(knight, illegalSpace)
expect(illegalSpace).not.toHaveTextContent('♘')
})
})
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { CSSProperties, FC } from 'react'
import { CSSProperties, FC, memo } from 'react'
import { ConnectDragSource, DragSourceMonitor } from 'react-dnd'
import { DragSource, DragSourceConnector } from 'react-dnd'

Expand All @@ -22,17 +22,19 @@ export interface BoxProps {
isDragging: boolean
}

export const Box: FC<BoxProps> = ({
export const Box: FC<BoxProps> = memo(function Box({
name,
isDropped,
isDragging,
connectDragSource,
}) => {
}) {
const opacity = isDragging ? 0.4 : 1
return connectDragSource(
<div style={{ ...style, opacity }}>{isDropped ? <s>{name}</s> : name}</div>,
<div role="Box" style={{ ...style, opacity }}>
{isDropped ? <s>{name}</s> : name}
</div>,
)
}
})

export default DragSource(
(props: BoxProps) => props.type,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { FC, useState, useCallback } from 'react'
import { FC, memo, useState, useCallback } from 'react'
import { NativeTypes } from 'react-dnd-html5-backend'
import Dustbin from './Dustbin'
import Box from './Box'
Expand Down Expand Up @@ -30,7 +30,7 @@ export interface ContainerState {
boxes: BoxSpec[]
}

export const Container: FC = () => {
export const Container: FC = memo(function Container() {
const [dustbins, setDustbins] = useState<DustbinState[]>([
{ accepts: [ItemTypes.GLASS], lastDroppedItem: null },
{ accepts: [ItemTypes.FOOD], lastDroppedItem: null },
Expand Down Expand Up @@ -97,4 +97,4 @@ export const Container: FC = () => {
</div>
</div>
)
}
})
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { CSSProperties, FC } from 'react'
import { CSSProperties, FC, memo } from 'react'
import { ConnectDropTarget, DropTargetMonitor } from 'react-dnd'
import { DropTarget } from 'react-dnd'

Expand Down Expand Up @@ -26,13 +26,13 @@ export interface DustbinProps {
connectDropTarget: ConnectDropTarget
}

export const Dustbin: FC<DustbinProps> = ({
export const Dustbin: FC<DustbinProps> = memo(function Dustbin({
accepts,
isOver,
canDrop,
connectDropTarget,
lastDroppedItem,
}) => {
}) {
const isActive = isOver && canDrop

let backgroundColor = '#222'
Expand All @@ -43,7 +43,11 @@ export const Dustbin: FC<DustbinProps> = ({
}

return connectDropTarget(
<div style={{ ...style, backgroundColor }}>
<div
ref={connectDropTarget}
style={{ ...style, backgroundColor }}
role="Dustbin"
>
{isActive
? 'Release to drop'
: `This dustbin accepts: ${accepts.join(', ')}`}
Expand All @@ -53,7 +57,7 @@ export const Dustbin: FC<DustbinProps> = ({
)}
</div>,
)
}
})

export default DropTarget(
(props: DustbinProps) => props.accepts,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,55 +1,45 @@
import Example from '..'
import DndDustbin, { DustbinProps } from '../Dustbin'
import DndBox, { BoxProps } from '../Box'
import {
wrapInTestContext,
simulateDragDropSequence,
} from 'react-dnd-test-utils'
import { mount } from 'enzyme'
import { DndComponent as DndC } from 'react-dnd'
import { wrapWithBackend, fireDragDrop } from 'react-dnd-test-utils'
import { render } from '@testing-library/react'

describe('Dustbin: Multiple Targets', () => {
it('behaves as expected', () => {
const [Wrapped, getBackend] = wrapInTestContext(Example)
const root = mount(<Wrapped />)
it('behaves as expected', async () => {
const TestExample = wrapWithBackend(Example)
const rendered = render(<TestExample />)

// Verify that all of the key components mounted
const dustbins = root.find(DndDustbin)
const boxes = root.find(DndBox)
const dustbins = await rendered.findAllByRole('Dustbin')
const boxes = await rendered.findAllByRole('Box')
expect(dustbins.length).toEqual(4)
expect(boxes.length).toEqual(3)

window.alert = jest.fn()

// Bin Types
const glassBin: DndC<DustbinProps> = dustbins.at(0).instance() as any
const foodBin: DndC<DustbinProps> = dustbins.at(1).instance() as any
// const paperGlassUrlBin: DndC<DustbinProps> = dustbins
// .at(2)
// .instance() as any
// const paperFileBin: DndC<DustbinProps> = dustbins.at(3).instance() as any
const glassBin = dustbins[0]
const foodBin = dustbins[1]

// Box Types
const bottleBox: DndC<BoxProps> = boxes.at(0).instance() as any
const bananaBox: DndC<BoxProps> = boxes.at(1).instance() as any
// const magazineBox: DndC<BoxProps> = boxes.at(2).instance() as any
const bottleBox = boxes[0] as HTMLDivElement
const bananaBox = boxes[1]

// interactions

// drop bottle into glass bin
simulateDragDropSequence(bottleBox, glassBin, getBackend())
expect(glassBin.props.lastDroppedItem.name).toEqual(bottleBox.props.name)
await fireDragDrop(bottleBox, glassBin)
expect(glassBin.textContent).toContain(JSON.stringify({ name: 'Bottle' }))

// food won't drop into the glass bin
simulateDragDropSequence(bananaBox, glassBin, getBackend())
expect(glassBin.props.lastDroppedItem.name).toEqual(bottleBox.props.name)
await fireDragDrop(bananaBox, glassBin)
expect(glassBin.textContent).toContain(JSON.stringify({ name: 'Bottle' }))

// glass won't drop into the food box...
simulateDragDropSequence(bottleBox, foodBin, getBackend())
expect(foodBin.props.lastDroppedItem).toBeNull()
await fireDragDrop(bottleBox, foodBin)
expect(foodBin.textContent).not.toContain('Last dropped')

// but some food will work
simulateDragDropSequence(bananaBox, foodBin, getBackend())
expect(foodBin.props.lastDroppedItem.name).toEqual(bananaBox.props.name)
await fireDragDrop(bananaBox, foodBin)
expect(foodBin.textContent).toContain('Last dropped')
expect(foodBin.textContent).toContain(JSON.stringify({ name: 'Banana' }))
})
})
21 changes: 15 additions & 6 deletions packages/examples-decorators/src/01-dustbin/single-target/Box.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,12 @@ export interface BoxProps {
const Box: FC<BoxProps> = ({ name, isDragging, connectDragSource }) => {
const opacity = isDragging ? 0.4 : 1
return (
<div ref={connectDragSource} style={{ ...style, opacity }}>
<div
ref={connectDragSource}
role={'Box'}
data-testid={`box-${name}`}
style={{ ...style, opacity }}
>
{name}
</div>
)
Expand All @@ -32,7 +37,9 @@ const Box: FC<BoxProps> = ({ name, isDragging, connectDragSource }) => {
export default DragSource(
ItemTypes.BOX,
{
beginDrag: (props: BoxProps) => ({ name: props.name }),
beginDrag: (props: BoxProps) => {
return { name: props.name }
},
endDrag(props: BoxProps, monitor: DragSourceMonitor) {
const item = monitor.getItem()
const dropResult = monitor.getDropResult()
Expand All @@ -42,8 +49,10 @@ export default DragSource(
}
},
},
(connect: DragSourceConnector, monitor: DragSourceMonitor) => ({
connectDragSource: connect.dragSource(),
isDragging: monitor.isDragging(),
}),
(connect: DragSourceConnector, monitor: DragSourceMonitor) => {
return {
connectDragSource: connect.dragSource(),
isDragging: monitor.isDragging(),
}
},
)(Box)
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,11 @@ const Dustbin: FC<DustbinProps> = ({ canDrop, isOver, connectDropTarget }) => {
}

return (
<div ref={connectDropTarget} style={{ ...style, backgroundColor }}>
<div
ref={connectDropTarget}
style={{ ...style, backgroundColor }}
role="Dustbin"
>
{isActive ? 'Release to drop' : 'Drag a box here'}
</div>
)
Expand Down
Loading

0 comments on commit 75b37f9

Please sign in to comment.