通过道具使组件在测试中反应

时间:2019-02-06 11:08:27

标签: reactjs redux react-redux enzyme

我正在尝试测试需要一些道具才能呈现html的类组件,但不确定为什么不起作用。我以开玩笑的方式开始测试并立即做出反应,因此我没有真正的经验。我缺少什么?

测试组件

const mockStore = configureMockStore();
const store = mockStore({});
describe("Pokemon detail", () => {
    const mockPokemon =  {
        sprites: {
            back_default:
              "https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/back/132.png"
          },
          name: "ditto",
          abilities: [
            {
              ability: {
                name: "imposter",
                url: 'https://pokeapi.co/api/v2/ability/150/"'
              }
            },
            {
              ability: {
                name: "imposter",
                url: "https://pokeapi.co/api/v2/ability/150/"
              }
            }
          ],
          types: [
            {
              type: {
                name: "normal"
              }
            }
          ]

      }
  const wrapper = mount(
    <Provider store={store}>
      <PokemonDetail pokemon={mockPokemon} />
    </Provider>
  );
  expect(wrapper).toMatchSnapshot();
});

错误消息是这个

TypeError: Cannot read property 'sprites' of undefined

         render() {
          <h1>oi</h1>
        if (this.props.pokemon.sprites) {
                                 ^
      const habilidades = this.props.pokemon.abilities.map(element => {
            return <li key={element.ability.url}>{element.ability.name}</li>;
         });

经过测试的组件

class PokemonDetail extends React.Component {
  render() {
    if (this.props.pokemon.sprites) {
      const habilidades = this.props.pokemon.abilities.map(element => {
        return <li key={element.ability.url}>{element.ability.name}</li>;
      });
      const tipos = this.props.pokemon.types.map(element => {
        return <li key={element.type.url}>{element.type.name}</li>;
      });

      return (
        <div className="ui card">
          <div className="image">
            <img src={this.props.pokemon.sprites.back_default} />
          </div>
          <div className="content">
            <a className="header">{this.props.pokemon.name}</a>
          </div>
          <button
            onClick={() => this.props.favoritePokemon(this.props.pokemon.name)}
            className="ui button primary"
          >
            Add
          </button>
        </div>
      );
    }
    return <div />;
  }
}
const mapStateToProps = state => {
  return { pokemon: state.pokemon };
};
export default connect(mapStateToProps,{favoritePokemon})(PokemonDetail);

不知道为什么道具对象上没有发生带有假数据的模拟宠物小精灵。...似乎对我来说正确

1 个答案:

答案 0 :(得分:1)

由于PokemonDetail是Redux连接的组件,并且pokemon道具是由Redux处理的,因此<PokemonDetail pokemon={mockPokemon} />中的道具将被Redux覆盖。

相反,该对象应作为Redux存储的一部分传递:

  const store = mockStore({ pokemon: mockPokemon });

  const wrapper = mount(
    <Provider store={store}>
      <PokemonDetail />
    </Provider>
  );