javascript - Test Switch Case - Unit testing - Stack Overflow

I am new to unit testing and I ran into the this case.I am using JEST and Enzyme - REACT JSI am famili

I am new to unit testing and I ran into the this case. I am using JEST and Enzyme - REACT JS

I am familiar calling clicks and onChange events but not sure how to set up a test for the following:

updateUser = (e) => {
  var tempUser = this.state.user;

  switch(e.target.id){
     case "firstName":
           tempUser.FirstName = e.target.value;
           break;
     case "lastName":
           tempUser.LastName = e.target.value;
           break;
     case "email":
           tempUser.Email = e.target.value;
           break;
      case "userName":
           tempUser.Username = e.target.value;
           break;
      default:
           break;
    }

this.setState({
    user: tempUser,
   })
}

So I tried to apply the same set up I have been using to test updateUser - not sure if its the correct approach.

describe(' Test', () => {
let wrapper;

 beforeEach(() => wrapper = shallow(<Component {...baseProps} />));

it('UpdateUser method', () => {
 wrapper.instance().updateUser = jest.fn();
 wrapper.setState({
   user:{
         tempUser :{
            FirstName: "",
            LastName:"",
            Email:"",
            Username:"",
          },
      },
  }),
wrapper.update();
expect(wrapper.instance().updateUser).toBeDefined();
expect(wrapper.state().user).toEqual({}); 
})

Thanks for the help - hope to learn how to test switch cases and get this test to pass.

I am new to unit testing and I ran into the this case. I am using JEST and Enzyme - REACT JS

I am familiar calling clicks and onChange events but not sure how to set up a test for the following:

updateUser = (e) => {
  var tempUser = this.state.user;

  switch(e.target.id){
     case "firstName":
           tempUser.FirstName = e.target.value;
           break;
     case "lastName":
           tempUser.LastName = e.target.value;
           break;
     case "email":
           tempUser.Email = e.target.value;
           break;
      case "userName":
           tempUser.Username = e.target.value;
           break;
      default:
           break;
    }

this.setState({
    user: tempUser,
   })
}

So I tried to apply the same set up I have been using to test updateUser - not sure if its the correct approach.

describe(' Test', () => {
let wrapper;

 beforeEach(() => wrapper = shallow(<Component {...baseProps} />));

it('UpdateUser method', () => {
 wrapper.instance().updateUser = jest.fn();
 wrapper.setState({
   user:{
         tempUser :{
            FirstName: "",
            LastName:"",
            Email:"",
            Username:"",
          },
      },
  }),
wrapper.update();
expect(wrapper.instance().updateUser).toBeDefined();
expect(wrapper.state().user).toEqual({}); 
})

Thanks for the help - hope to learn how to test switch cases and get this test to pass.

Share Improve this question edited Feb 28, 2019 at 14:31 skyboyer 23.8k7 gold badges62 silver badges71 bronze badges asked Feb 28, 2019 at 14:24 user 9191user 9191 7475 gold badges15 silver badges34 bronze badges 3
  • @skyboyer any advice ? work something out based on my answer – user 9191 Commented Feb 28, 2019 at 14:43
  • in general my advice: calling updateUser through props and validate render() changed ponent accordingly. mutating state makes your ponent unstable while accessing state directly in tests makes tests harder to maintain. I'd not do that. to show some code I need at least understand how updateUser is bound to element and how your ponent is rendered. – skyboyer Commented Feb 28, 2019 at 15:50
  • Should i add the code and the test code inside of a codesandbox – user 9191 Commented Feb 28, 2019 at 16:02
Add a ment  | 

2 Answers 2

Reset to default 1

There is example how to simulate click on button with shallow rendering https://airbnb.io/enzyme/docs/api/shallow.html#shallow-rendering-api.

Also if you are using old state use callback function. Do not mutate state. Or you can make even simpler.

updateUser = (e) => {
  let key;
  switch(e.target.id){
       case "firstName":
             key = "FirstName";
             break;
       case "lastName":
            key = "LastName";
             break;
       case "email":
            key = "Email";
             break;
        case "userName":
              key = "Username";
             break;
        default:
             return null;
      }
  this.setState({[key]: e.target.value})
}

it's tricky to speculate without actual code(I mean render() method).

Suppose it looks like(I've skipped switch/case to make it shorter)

updateState = ({target: { value, id }}) => {
    this.setState({
        [id]: value,
    });
}

render() {
    return (<>
      <input value={this.state.email} id="email" onChange={this.updateState} />
      <input value={this.state.firstName} id="firstName" onChange={this.updateState} />
      <input value={this.state.lastName} id="lastName" onChange={this.updateState} />
      <input value={this.state.age} id="age" onChange={this.updateState} />
      <div id="raw_output">{JSON.stringify(this.state)}</div>
    </>);
}

Then focusing on testing render()'s result does not need you to mock any functions:

function updateFieldById(wrapper, id, value) {
    wrapper.find(id).simulate('change', { target: { id, value } });
}

it('updates state after each field changed', () => {
    const wrapper = shallow(<Comp />);
    // checking start output with default input
    expect(wrapper.find('#raw_input').props().children).toMatchSnapshot();
    updateFieldById(wrapper, 'email', '_email_mock_');
    expect(wrapper.find('#raw_input').props().children).toMatchSnapshot();
    updateFieldById(wrapper, 'firstName', '_fn_mock_');
    expect(wrapper.find('#raw_input').props().children).toMatchSnapshot();
    updateFieldById(wrapper, 'lastName', '_ln_mock_');
    expect(wrapper.find('#raw_input').props().children).toMatchSnapshot();
    updateFieldById(wrapper, 'age', '999');
    expect(wrapper.find('#raw_input').props().children).toMatchSnapshot();
});

Sure instead of using toMatchSnapshot() you may check for any element's existence or verify particular text value like

    expect(wrapper.find('#fullName').props().children).toEqual('firstName lastName');

Also you may to split test case on by-field basis.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745216519a4617049.html

相关推荐

  • javascript - Test Switch Case - Unit testing - Stack Overflow

    I am new to unit testing and I ran into the this case.I am using JEST and Enzyme - REACT JSI am famili

    3小时前
    40

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信