Ad

Jest|Enzyme How To Expect Any String On A DefaultValue In Input

- 1 answer

I'm new to the whole testing thing and have been reading through the airbnb / jest documentation trying to figure out how to make this test work and currently nothing is coming to mind that successfully runs.

I have a defaultValue in my snapshot that equals a new randomly generated string every time the tests are run. I'm curious how I can target this input's defaultValue and set it to expect any string.

Test:

expect(toJson(wrapper)).toMatchSnapshot({'[defaultValue]'.expect.any('string')});

Source:

<input
  ref={this.myInput}
  type="text"
  placeholder=" Enter your name..."
  defaultValue={getFunName()}
/>
Ad

Answer

As long as you have randomly generated data changing the result of what is rendered, snapshots will fail. Snapshots are meant to check if anything changed between tests.

Snapshot tests are a very useful tool whenever you want to make sure your UI does not change unexpectedly. https://jestjs.io/docs/en/snapshot-testing

Instead of a snapshot, you can selectively check properties of the rendered component.

it('should be super sweet', () => {
  // Render the component
  const wrapper = shallow(<App />)

  // Find a part of it you want to examine
  const input = wrapper.find('input').first()

  // Check that it looks the way you want
  expect(input.prop('type')).toBe('text')
  expect(input.prop('placeholder')).toBe(' Enter your name...')
});

When trying to snapshot a large component, where inner components being rascally, you can look at mocking the child components (assuming they are imported and not defined inline). If it's one big render with lots of markup, you should look at deconstructing it into more bite-sized components to make it more testable among many other reasons.

Nested Component

Given a component you want to snapshot that has unpredictable children...

const getFunName = () => `${Math.random()} name`

const App = () => (
  <div>
    <h1>This component rocks my socks.</h1>
    <div>
      <input defaultValue={getFunName()} />
    </div>
  </div>
)

Move the child into its own component.

const UnpredictableChild = () => (
  <div>
    <input defaultValue={getFunName()} />
  </div>
)

const App = () => (
  <div>
    <h1>This component rocks my socks.</h1>
    <UnpredictableChild />
  </div>
)

Then move into its own file.

import UnpredictableChild from './UnpredictableChild'

const App = () => (
  <div>
    <h1>This component rocks my socks.</h1>
    <UnpredictableChild />
  </div>
)
Ad
source: stackoverflow.com
Ad