1

I want to test the error state of a React Component with Enzyme mount. The error isnt displayed even though the State is set.

This is the render Method of the React Component

  render() {

    return (
      <div>
        <div>
          <h1>Signup</h1>

          {this.state.error ? <p>{this.state.error}</p> : undefined}

          <form onSubmit={this.onSubmit}>
            <input type="text" ref="username" name="username" placeholder="Username"/>
            <input type="email" ref="email" name="email" placeholder="Email"/>
            <input type="password" ref="password" name="password" placeholder="Password"/>
            <button>Create Account</button>
          </form>

          <p><Link to="/login">Already have an account?</Link></p>
        </div>
      </div>
    )

  }

This is the Test with Mocha and Enzyme

    it('should show error message', function () {

      const error = 'This is not working'
      const spy2 = expect.createSpy()

      const wrapper2 = Enzyme.mount(
        <MemoryRouter>
          <Signup
            createUser={spy2}
          />
        </MemoryRouter>
      )

      // Access Signup Component inside Memory Router
      const component = wrapper2.find(Signup)

      component.setState({error})
      expect(component.find('p').first().text()).toBe(error)
    })

I expect that the text of the error paragraph matches with the set error state message

diadamalol
  • 198
  • 15
  • I am not sure whether the transition from `setState` to `render` to updating virtual DOM is blocking or non-blocking. If it is non-blocking then maybe you call `expect` just "too early" and the component is marked as dirty and maybe not yet rendered or the DOM is not yet updated? Maybe [this](https://stackoverflow.com/a/24719294/3098783) helps? Would it work if you call `expect` after a few miliseconds using `setTimeout`? – Jankapunkt Apr 14 '19 at 20:04

0 Answers0