【问题标题】:React jest testing Google Maps Api , Uncaught TypeError: this.autocomplete.addListener is not a functionReact jest testing Google Maps Api , Uncaught TypeError: this.autocomplete.addListener is not a function
【发布时间】:2020-01-12 01:07:54
【问题描述】:

我开发了一个 React Google Maps Autocomplete 组件。它工作正常,但在开玩笑测试中失败。我想出 this.autocomplete.addListener 不是组件本身及其父组件上的函数。

大多数有类似问题的线程都是关于 ReferenceError: google is not defined 错误。我通过在 setupTests.js 上定义 google 解决了这个问题

window.google = {
  maps: {
    places: {
      Autocomplete: class {}
    }
  }
};

我想这个问题不相关,即使我尝试了很多方法,我也找不到解决方案。测试失败的 ComponentDidMount 方法如下。

componentDidMount() {
    this.autocomplete = new google.maps.places.Autocomplete(
      this.autocompleteInput.current,
      {
        types: ["geocode"],
        componentRestrictions: { country: "uk" },
        fields: ["formatted_address", "geometry"]
      }
    );
    this.autocomplete.addListener("place_changed", this.handlePlaceChanged);
  }

另外,我的测试文件在下面

describe("Autocomplete component", () => {
  it("renders without crashing", () => {
    const div = document.createElement("div");
    ReactDOM.render(<Autocomplete />, div);
    ReactDOM.unmountComponentAtNode(div);
  });
});

我在运行 npm test 时遇到的错误如下。

错误:未捕获 [TypeError:this.autocomplete.addListener 不是函数]

我是开玩笑测试的新手。我很感激任何帮助。谢谢。

【问题讨论】:

  • 是的,我遇到了同样的问题。

标签: reactjs google-maps testing jestjs


【解决方案1】:

我想,我找到了解决方案。在模拟 setupTests.js 时,添加 addListener 函数会有所帮助。如果您在 component.test.js 父组件中编写此代码块,则会不断收到相同的错误。所以在 setupTests.js 中编写它可以解决问题。

window.google = {
  maps: {
    places: {
      Autocomplete: function() {
        return { addListener: jest.fn() };
      },
      event: { trigger: jest.fn() }
    }
  }
};

【讨论】:

    猜你喜欢
    • 2020-11-24
    • 2019-04-29
    • 2020-07-11
    • 1970-01-01
    • 1970-01-01
    • 2018-12-31
    • 2017-03-11
    • 2023-02-17
    • 1970-01-01
    相关资源
    最近更新 更多