如何用开玩笑测试chrome.storage.sync.get()值?

发布于 2025-01-27 08:30:38 字数 1126 浏览 4 评论 0原文

我的React组件包含一个类似的处理程序,该处理程序在按钮的on Click函数中称为:

const handleSaveInformationButtonClick = () => {
    chrome.storage.sync.set({ information }, () => {
      // do something
    })
  }

我想使用开玩笑和React-Testing-library在存储中测试键“信息”的值。我写了这项测试:

test("save new information into browser storage", () => {
    const { rerender } = render(<MyComponent />);
    const inputInformation = screen.getByTestId("main-input");
    const buttonSave = screen.getByTestId("main-button");
    const newInformation = "something here";
    fireEvent.change(inputInformation, { target: { value: newInformation } });
    fireEvent.click(buttonSave);
    rerender(<MyComponent />);
    expect(chrome.storage.sync.get("information")).toBe(newInformation);
});

我将Chrome添加为包装中的全局变量。JSON:

"jest": {
    "globals": {
      "chrome": {}
    },
    ...

但是,当我运行测试时,我得到了:

TypeError: Cannot read property 'sync' of undefined
on line : 'expect(chrome.storage.sync.get("information")).toBe(newInformation);'

我该如何测试?

My React component contains a handler like this one which is called in a onClick function of a button:

const handleSaveInformationButtonClick = () => {
    chrome.storage.sync.set({ information }, () => {
      // do something
    })
  }

I would like to test the value of the key "information" in the storage using Jest and react-testing-library. I wrote this test :

test("save new information into browser storage", () => {
    const { rerender } = render(<MyComponent />);
    const inputInformation = screen.getByTestId("main-input");
    const buttonSave = screen.getByTestId("main-button");
    const newInformation = "something here";
    fireEvent.change(inputInformation, { target: { value: newInformation } });
    fireEvent.click(buttonSave);
    rerender(<MyComponent />);
    expect(chrome.storage.sync.get("information")).toBe(newInformation);
});

I added chrome as global variable inside package.json :

"jest": {
    "globals": {
      "chrome": {}
    },
    ...

but when I run the test, I got :

TypeError: Cannot read property 'sync' of undefined
on line : 'expect(chrome.storage.sync.get("information")).toBe(newInformation);'

How can I test this please ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文