-
Notifications
You must be signed in to change notification settings - Fork 23
/
storybook.test.js
60 lines (49 loc) · 1.85 KB
/
storybook.test.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
import './utils/testUtils/matchMediaMock'
import 'jest-specific-snapshot'
const glob = require('glob')
const path = require('path')
import React from 'react'
import { render } from '@testing-library/react'
import { composeStories } from '@storybook/testing-react'
const SNAPSHOTS_FOLDER = '__snapshots__'
const SNAPSHOT_EXT = '.js.snap'
const STORIES_GLOB = '{tokens,atoms,molecules,layout}/**/*.stories.@(js|mdx)'
const getStoryPaths = (file) => {
const resolvedFilePath = path.resolve(__dirname, file)
const dirnamePath = path.dirname(resolvedFilePath)
return { resolvedFilePath, dirnamePath }
}
const getStoriesModules = (globPath) => {
try {
return glob.sync(globPath).map((filePath) => ({
module: require(getStoryPaths(filePath).resolvedFilePath),
filePath,
}))
} catch (error) {
console.error('Error reading story files using a glob pattern', error)
}
}
const getComponentNameStoryFilePath = (filePath) => {
return filePath.split('/').pop().split('.').shift()
}
const getSnapshotPath = (filePath) => {
const { dirnamePath } = getStoryPaths(filePath)
const componentName = getComponentNameStoryFilePath(filePath)
return `${dirnamePath}/${SNAPSHOTS_FOLDER}/${componentName}${SNAPSHOT_EXT}`
}
const storiesModules = getStoriesModules(STORIES_GLOB)
describe('[ storybook ]', () => {
storiesModules.forEach(({ module, filePath }) => {
const { default: _default, ...stories } = module
const composedStories = composeStories(stories)
describe(`[ ${_default.title} ]`, () => {
Object.entries(composedStories).forEach(([story, Component]) => {
it(`should render ${story}`, () => {
const { asFragment } = render(<Component {..._default.args} />)
const snapshotPath = getSnapshotPath(filePath)
expect(asFragment()).toMatchSpecificSnapshot(snapshotPath)
})
})
})
})
})