Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(common): add test helper #307

Merged
merged 5 commits into from
Dec 1, 2023
Merged
Show file tree
Hide file tree
Changes from 4 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
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/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,167 @@
import {
isAssetModalChangeMessage,
isGetContextMessage,
isHeightChangeMessage,
isModalChangeMessage,
isPluginLoadedMessage,
isValueChangeMessage,
} from '@storyblok/field-plugin'
import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { describe, test, expect, vi } 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: '',

const fakeContainer = (sendToFieldPlugin) => {
const schema = {
field_type: 'test-field-plugin',
options: [],
}
let height = undefined
let uid = 'test-uid'
let model = 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'

const stateMessage = ({ action, callbackId }) => ({
callbackId: callbackId,
schema,
model,
isModalOpen,
uid,
blockId,
story: {
content: {},
},
storyId: undefined,
blockUid: undefined,
token: undefined,
uid: '',
},
actions: {
setContent: vi.fn(),
setModalOpen: vi.fn(),
requestContext: vi.fn(),
selectAsset: vi.fn(),
},
language,
storyId,
spaceId,
token,
action,
})

return {
receive: ({ data, origin }) => {
if (isPluginLoadedMessage(data)) {
sendToFieldPlugin(
stateMessage({
action: 'loaded',
callbackId: data.callbackId,
}),
Copy link
Contributor

Choose a reason for hiding this comment

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

instead of if --> if else --> if else ..... I think early exit of the function could make this logic a bit more readable.

      
      if (isPluginLoadedMessage(data)) {
        listener(
          stateMessage({
            action: 'loaded',
            callbackId: data.callbackId,
          }),
           return;
          }
          
      if(isValueChangeMessage(data)){
            ....
            return;
          }

)
} 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
sendToFieldPlugin(
stateMessage({
action: 'state-changed',
callbackId: data.callbackId,
}),
)
} else if (isAssetModalChangeMessage(data)) {
sendToFieldPlugin({
action: 'asset-selected',
uid,
filename: 'https://...',
field: '',
callbackId: data.callbackId,
})
} else if (isGetContextMessage(data)) {
sendToFieldPlugin({
action: 'get-context',
uid,
callbackId: data.callbackId,
story: {
content: {},
},
})
} else {
console.warn(
`Container received unknown message from plugin: ${JSON.stringify(
data,
)}`,
)
}
},
}
}

const setup = () => {
let handleEvent
const listener = (data) => {
handleEvent({ data })
}
const container = fakeContainer(listener)
global.ResizeObserver = class ResizeObserver {
Copy link
Contributor

Choose a reason for hiding this comment

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

We could extract the observer mocking in a separate method, to shorten the setup function a bit.

observe() {
// do nothing
}
unobserve() {
// do nothing
}
disconnect() {
// do nothing
}
}
vi.stubGlobal('parent', {
...global.parent,
postMessage: vi.mocked((data: unknown, 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)
}
})
}

describe('FieldPluginExammple', () => {
test('should work', () => {
vi.mocked(useFieldPlugin<number | undefined>).mockReturnValue(
fieldPluginDefault,
)
afterEach(() => {
vi.unstubAllGlobals()
})

test('should render the component', () => {
setup()
render(<FieldPlugin />)
const headline = screen.getByText('Field Value')
expect(headline).toBeInTheDocument()
})

test('should increase the counter', async () => {
setup()
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')
})
})
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