Search code examples
reactjsstyled-componentsvitestorybookvitest

How to configure Vitest and Styled Components?


I have react project which created with vite and it use typescript. The project use storybook as well and styled componenets when I run test with vitest I am getting the following error

 TypeError: Cannot read properties of undefined (reading 'borderRadius')
  src/stories/atoms/button/Button.styles.tsx:8:31
         border-radius: ${props => props.rounded?
                 '50%' :
                 props.theme.spacing.borderRadius.medium + 'px'};

in jest we could use jest-styled-components package but I don't how i could solve this with vitest


Solution

  • After long search I found that if i use shallow from enzyme it works fine

    import { shallow } from 'enzyme'
    import type { ShallowWrapper } from 'enzyme'
    

    this my test file and it works fine

    describe('Button', () => {
        let wrapper: ShallowWrapper
        const mockedOnSubmit = vi.fn()
    
    
    beforeEach(() => {
        wrapper = shallow(<Button label="Primary" variant="primary" onClick={mockedOnSubmit} size="medium"/>)
    })
    
    test('should render with correct props', () => {
        expect(wrapper).toBeDefined()
        expect(wrapper.name()).toBe('styled.button')
    
        expect(wrapper.text()).toBe('Primary  ')
        expect(wrapper.prop('variant')).toBe('primary')
        expect(wrapper.prop('size')).toBe('medium')
    })
    
    test('should invoke onClick prop by clicking on the button', () => {
        wrapper.simulate('click')
        expect(mockedOnSubmit).toHaveBeenCalled()
    })
    
    test('should match snapshot', () => {
        expect(wrapper).toMatchSnapshot()
    })
    
    });