S_learner
S_learner

Reputation: 334

Test stateful react component with the use of Jest only (without using React Testing Library or Enzyme)

Is it possible to test stateful react component with the use of Jest only? I could not find any examples where this can be achieved without using any other library like Enzyme or React testing library.

The sample code that I would like to test,

import React,{Component} from 'react';

class SampleComponent extends Component {

  constructor(props) {
    super(props)
    this.state = {
      username: '',
      password: '',
      loginMessage: ''
    }

    this.onChange = this.onChange.bind(this);
    this.onSubmit = this.onSubmit.bind(this);
  }

  onChange(event) {
    this.setState({
      [event.target.name] : event.target.value
    })
  }

  onSubmit(event) {
    if(this.state.password === 'password') {
          this.setState({
            loginMessage: 'Login Successfully'
          })
    } else {
          this.setState({
            loginMessage: 'Login Failed due to incorrect password'
          })
    }
    event.preventDefault();
  }

  render() {
    return (
      <React.Fragment>
        <p>Hello React!!!</p>
        <form onSubmit={this.onSubmit}>
          <input placeholder="user" type="text" name="username" value={this.state.username} onChange={this.onChange}/>
          <input placeholder="password" type="password" name="password" value={this.state.password} onChange={this.onChange}/>
          <button type="submit">Submit</button>
        </form>
        <h6>{this.state.loginMessage}</h6>
      </React.Fragment>
    );
  }
}

export default SampleComponent

Upvotes: 0

Views: 607

Answers (1)

jjanczyk
jjanczyk

Reputation: 481

Technically it's just a class so you can always create a new instance of it via new operator in your test: new SampleComponent(props) and then call some methods on it or access state.

However, why would you want to do this? Reason why you cannot find any examples is that tt's extremally bad practice to test components like this. You are missing a lot of stuff that those libraries are providing and that you have to code yourself. It wouldn't be properly mounted, so state might not work properly. And you are testing implementation details (see this article why it's bad idea).

If you just don't like Enzyme or React-Testing-Library you can always check lower level Test Renderer from React team.

I don't know your specific case, but I would really suggest to use some library as it simplifies testing.

Upvotes: 1

Related Questions