Skip to content

Commit

Permalink
feat(common): add test helper (#307)
Browse files Browse the repository at this point in the history
* WIP

* chore(lib): release @storyblok/field-plugin@1.0.0 (#305)

* fix test and clean up

* renames

* fix(common): fix type errors in test helper (#320)

* clean up test helper WIP

* improve types

* update snapshot
  • Loading branch information
eunjae-lee authored Dec 1, 2023
1 parent 2d5b413 commit 7d2f396
Show file tree
Hide file tree
Showing 10 changed files with 1,374 additions and 557 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@
"dev:js": "yarn dev:template js",
"dev:vue2": "yarn dev:template vue2",
"dev:vue3": "yarn dev:template vue3",
"test:template": "yarn workspace field-plugin-${0}-template test --config node_modules/.${0}-vite.config.ts",
"test:template": "yarn workspace field-plugin-${0}-template test --config node_modules/.${0}-vite.config.ts --ui",
"test:react": "yarn test:template react",
"test:js": "yarn test:template js",
"test:vue2": "yarn test:template vue2",
Expand Down
2 changes: 2 additions & 0 deletions packages/cli/src/commands/__tests__/add.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ describe('add', () => {
"index.html",
"package.json",
"src",
"test",
"tsconfig.json",
"tsconfig.node.json",
"vite.config.ts",
Expand Down Expand Up @@ -87,6 +88,7 @@ describe('add', () => {
"index.html",
"package.json",
"src",
"test",
"tsconfig.json",
"tsconfig.node.json",
"vite.config.ts",
Expand Down
2 changes: 2 additions & 0 deletions packages/cli/templates/react/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,13 @@
"devDependencies": {
"@testing-library/jest-dom": "6.1.4",
"@testing-library/react": "14.0.0",
"@testing-library/user-event": "14.5.1",
"@types/react": "^18.0.28",
"@types/react-dom": "^18.0.11",
"@typescript-eslint/eslint-plugin": "6.1.0",
"@typescript-eslint/parser": "6.1.0",
"@vitejs/plugin-react": "^4.1.0",
"@vitest/ui": "0.34.6",
"eslint": "latest",
"eslint-plugin-react": "7.30.0",
"jsdom": "22.1.0",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,12 @@ const Counter: FunctionComponent<{
return (
<div>
<h2>Field Value</h2>
<div className="counter-value">{count}</div>
<div
className="counter-value"
data-testid="count"
>
{count}
</div>
<button
className="btn w-full"
onClick={onIncrease}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,43 +1,27 @@
import { render, screen } from '@testing-library/react'
import { describe, test, expect, vi } from 'vitest'

import userEvent from '@testing-library/user-event'
import { describe, test, expect } from 'vitest'
import FieldPlugin from '.'
import { useFieldPlugin } from '@storyblok/field-plugin/react'
import { FieldPluginResponse } from '@storyblok/field-plugin'

vi.mock('@storyblok/field-plugin/react')

const fieldPluginDefault: FieldPluginResponse<number | undefined> = {
type: 'loaded',
data: {
isModalOpen: false,
content: undefined,
options: {},
spaceId: undefined,
storyLang: '',
story: {
content: {},
},
storyId: undefined,
blockUid: undefined,
token: undefined,
uid: '',
},
actions: {
setContent: vi.fn(),
setModalOpen: vi.fn(),
requestContext: vi.fn(),
selectAsset: vi.fn(),
},
}
import { setupFieldPlugin } from '../../../test'

describe('FieldPluginExammple', () => {
test('should work', () => {
vi.mocked(useFieldPlugin<number | undefined>).mockReturnValue(
fieldPluginDefault,
)
describe('FieldPluginExample', () => {
test('should render the component', () => {
const { cleanUp } = setupFieldPlugin()
render(<FieldPlugin />)
const headline = screen.getByText('Field Value')
expect(headline).toBeInTheDocument()
cleanUp()
})

test('should increase the counter', async () => {
const { cleanUp } = setupFieldPlugin()
const user = userEvent.setup()
render(<FieldPlugin />)
expect(screen.getByTestId('count').textContent).toEqual('0')
await user.click(screen.getByText('Increment'))
expect(screen.getByTestId('count').textContent).toEqual('1')
await user.click(screen.getByText('Increment'))
expect(screen.getByTestId('count').textContent).toEqual('2')
cleanUp()
})
})
151 changes: 151 additions & 0 deletions packages/cli/templates/react/test/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,151 @@
import {
isAssetModalChangeMessage,
isGetContextMessage,
isHeightChangeMessage,
isModalChangeMessage,
isPluginLoadedMessage,
isValueChangeMessage,
} from '@storyblok/field-plugin'

import { vi } from 'vitest'

const getContainer = (sendToFieldPlugin: (data: unknown) => void) => {
const schema = {
field_type: 'test-field-plugin',
options: [],
}
// @ts-ignore `height` is not used anywhere, but we keep it here.
let height = undefined
let uid = 'test-uid'
let model: any = undefined
let isModalOpen = false
let blockId = 'test-block-id'
let language = 'default'
let storyId = 'test-story-id'
let spaceId = 'test-space-id'
let token = 'test-token'
let story = {
content: {},
}

const stateMessage = ({
action,
callbackId,
}: {
action: 'loaded' | 'state-changed'
callbackId: string
}) => ({
callbackId: callbackId,
schema,
model,
isModalOpen,
uid,
blockId,
story,
language,
storyId,
spaceId,
token,
action,
})

return {
receive: ({
data,
}: {
data: { callbackId: string } & Record<string, any>
origin: string
}) => {
if (isPluginLoadedMessage(data)) {
sendToFieldPlugin(
stateMessage({
action: 'loaded',
callbackId: data.callbackId,
}),
)
} else if (isValueChangeMessage(data)) {
model = data.model
sendToFieldPlugin(
stateMessage({
action: 'state-changed',
callbackId: data.callbackId,
}),
)
} else if (isModalChangeMessage(data)) {
isModalOpen = data.status
sendToFieldPlugin(
stateMessage({
action: 'state-changed',
callbackId: data.callbackId,
}),
)
} else if (isHeightChangeMessage(data)) {
height = data.height
} else if (isAssetModalChangeMessage(data)) {
sendToFieldPlugin({
action: 'asset-selected',
uid,
filename: 'https://plugin-sandbox.storyblok.com/icon.svg',
callbackId: data.callbackId,
})
} else if (isGetContextMessage(data)) {
sendToFieldPlugin({
action: 'get-context',
uid,
callbackId: data.callbackId,
story,
})
} else {
console.warn(
`Container received unknown message from plugin: ${JSON.stringify(
data,
)}`,
)
}
},
}
}

export const setupFieldPlugin = () => {
let handleEvent: (event: MessageEvent<unknown>) => void
const container = getContainer((data: unknown) => {
// @ts-ignore
handleEvent({ data })
})
global.ResizeObserver = class ResizeObserver {
observe() {
// do nothing
}
unobserve() {
// do nothing
}
disconnect() {
// do nothing
}
}
vi.stubGlobal('parent', {
...global.parent,
postMessage: vi.mocked(
(data: { callbackId: string } & Record<string, any>, origin: string) => {
container.receive({ data, origin })
},
),
})
vi.stubGlobal('location', {
...window.location,
search: `?protocol=https%3A&host=plugin-sandbox.storyblok.com&uid=test-uid&preview=1`,
})

const addEventListenerFallback = global.addEventListener
vi.stubGlobal('addEventListener', (name: string, callback: EventListener) => {
if (name === 'message') {
handleEvent = callback
} else {
addEventListenerFallback.call(global, name, callback)
}
})

return {
cleanUp: () => vi.unstubAllGlobals(),
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,10 @@
<div class="counter-value">
{{ count }}
</div>
<button class="btn w-full" @click="onIncrease">
<button
class="btn w-full"
@click="onIncrease"
>
Increment
</button>
</div>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -99,13 +99,13 @@ export const createFieldPlugin: CreateFieldPlugin = ({

const cleanupHeightChangeListener = createHeightChangeListener(onHeightChange)

void initialize()

const cleanupMessageListenerSideEffects = createPluginMessageListener(
params.uid,
messageCallbacks,
)

void initialize()

return () => {
cleanupMessageListenerSideEffects()
cleanupHeightChangeListener()
Expand Down
1 change: 0 additions & 1 deletion scripts/prepare-dev-vite-configs.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,6 @@ const templates = (await fs.readdir('packages/cli/templates', { withFileTypes: t
for (const template of templates) {
const templatePath = `packages/cli/templates/${template}`
const newConfigPath = `${templatePath}/node_modules/.${template}-vite.config.ts`
console.log('💡 newConfigPath', newConfigPath)
await $`cp ${templatePath}/vite.config.ts ${newConfigPath}`

// eslint-disable-next-line functional/no-let
Expand Down
Loading

1 comment on commit 7d2f396

@vercel
Copy link

@vercel vercel bot commented on 7d2f396 Dec 1, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.