Jest间谍在React Native测试中工作不一致

时间:2019-08-14 16:28:48

标签: react-native jestjs

我正在使用react-native-testing-library

这有效:

it("should submit the form", () => {
      const mockCustomer = { name: "John Doe", address: mockAddress };
      const saveSpy = jest.spyOn(NewCustomerScreen.prototype, "saveCustomer");
      fireEvent.changeText(nameField, "John Doe");
      fireEvent.changeText(addressField, mockAddress);
      fireEvent.press(saveButton);
      expect(saveSpy).toHaveBeenCalledWith(mockCustomer);
      saveSpy.mockRestore();
    });

正在测试的代码摘录:

export class NewCustomerScreen extends React.Component<Props, State> {
  async saveCustomer(customer: Types.CustomerApiPostPayload) {
    console.log(customer);
    Keyboard.dismiss()
    await this.setState({isLoading: true})
    if (!(await this.fieldsValid(customer))) return;
    await this.props.createCustomer(customer);
  }

  render() {
    return (
        <Button
          title="Save Customer"
          onPress={this.saveCustomer.bind(this, this.customerFromState())}
          containerStyle={[styles.formItem, styles.buttonContainer]}
          loading={this.state.isLoading}
        />
    );
  }
}

但是,此间谍失败了,因为没有被称为:

it("should submit the form", () => {
      const searchSpy = jest.spyOn(
        SearchCustomerScreen.prototype,
        "handleSearch"
      );
      fireEvent.changeText(addressField, mockAddress);
      expect(searchButton).toBeDefined();
      fireEvent.press(searchButton);
      expect(searchSpy).toHaveBeenCalledWith(mockAddress);
      searchSpy.mockRestore();
    });

正在测试的代码摘录:

export class SearchCustomerScreen extends Component<Props, State> {
  async handleSearch() {
    if (!this.state.text) return;
    await this.props.searchCustomers({
      customers: this.props.customers,
      ...this.state
    });
    const results = this.props.searchResults;
    this.props.navigation.navigate("Results", { results });
  }

  render() {
    return (
          <Button
            title="Search"
            type="outline"
            onPress={this.handleSearch.bind(this)}
          />

实现似乎是相同的。所有其他组件/子组件测试工作正常。我也尝试将toHaveBeenCalled()的{​​{1}}用于相同的结果。

哦,代码可以在应用本身中工作。

0 个答案:

没有答案