使用Jest&Enzyme进行测试时设置URL参数

Ice*_*gth 4 reactjs jest enzyme

我的组件有:

 class Search extends Component {
  constructor(props) {
    super(props);
    this.state = {
      searchTerm:
        typeof this.props.match.params.searchTerm !== "undefined"
          ? this.props.match.params.searchTerm
          : ""
    };
  }
Run Code Online (Sandbox Code Playgroud)

测试是:

 test("Search should render correct amount of shows", () => {
  const component = shallow(<Search shows={preload.shows} />);
  expect(component.find(ShowCard).length).toEqual(preload.shows.length);
});
Run Code Online (Sandbox Code Playgroud)

我明白了

TypeError:无法读取undefined的属性'params'

我如何解决这个问题或如何在我的测试中设置查询参数?

rod*_*bbi 8

似乎在测试之外,Search组件match正确地接收道具.
在测试中浅呈现时,您可以将其作为道具传递:

test("Search should render correct amount of shows", () => {
 const match = { params: { searchTerm: 'foo' } }
 const component = shallow(<Search shows={preload.shows} match={match}/>);
 expect(component.find(ShowCard).length).toEqual(preload.shows.length);
});
Run Code Online (Sandbox Code Playgroud)

在这种情况下,你不是以一种糟糕的方式改变被测试的组件,你的测试用例只是发现了一个错误,这很好,应该针对测试,你通过实现默认道具来改进组件,更强大.


小智 6

您应该首先在 it/test 中定义一个位置。

\n
it(\'App init\', async () => {\n  const location = {\n    ...window.location,\n    search: \'?scope=3&elementId=25924\',\n  };\n  Object.defineProperty(window, \'location\', {\n    writable: true,\n    value: location,\n  })\n\n  \xe2\x80\xa6\xe2\x80\xa6\n})\n
Run Code Online (Sandbox Code Playgroud)\n