vendredi 30 juin 2017

How to understand unit test correctly?

Recently I am learning to test React with jest and enzyme, It seems hard to understand what a unit test is it, my code

import React from "react";

class App extends React.Component {
  constructor() {
    super();
    this.state = {
      value: ""
    };
    this.handleChange = this.handleChange.bind(this);
  }

  handleChange(e) {
    const value = e.target.value;
    this.setState({
      value
    });
  }
  render() {
    return <Nest value={this.state.value} handleChange={this.handleChange} />;
  }
}

export const Nest = props => {
  return <input value={props.value} onChange={props.handleChange} />;
};

export default App;

and my test

import React from "react";
import App, { Nest } from "./nest";

import { shallow, mount } from "enzyme";

it("should be goood", () => {
  const handleChange = jest.fn();
  const wrapper = mount(<App />);
  wrapper.find("input").simulate("change", { target: { value: "test" } });
  expect(handleChange).toHaveBeenCalledTimes(1);
});

By my understanding, when I simulate a change event on the input node,a mock handleChnage should be called, cause on the App, there is a handleClick function will be called at the real environment.

IMO, the mocked handleClick will intercept the handleClick on App,

if this is totally wrong, what's the right way to use mock fn and test the handleClick be called.

Another: I search a lot, read the similar situations, seem like this iscontra-Unit Test,
Probably I should test the two component separately, I can test both components, test the
<Nest value={value} handleChange={handleChange} />
by pass the props manually, and then handleChangeinvoked by simulate change
it passed test.
but how can I test the connection between the two? I read

some work is React Team's Work ...

I don't know which parts I have to test in this case, and Which parts react already tested and don't need me to test. That's confusing.

Aucun commentaire:

Enregistrer un commentaire