Skip to content

Instantly share code, notes, and snippets.

@ThaddeusJiang
Created July 27, 2018 00:10
Show Gist options
  • Save ThaddeusJiang/8882b6c507a03bef17be8e89df57abee to your computer and use it in GitHub Desktop.
Save ThaddeusJiang/8882b6c507a03bef17be8e89df57abee to your computer and use it in GitHub Desktop.
jest test chrome extension (mock chrome 对象)

因为 jest 运行环境没有 chrome 对象,我使用全剧对象。

  // package.json
  "jest": {
    "globals": {
      "chrome": {
        "extension": {}
      }
    }
  }

然后使用 Object.defineProperty Object.definePropertise 设置 chrome 中属性。

  it('test load css', () => {
    Object.defineProperty(chrome.extension, 'getURL', {
      value: jest.fn().mockImplementation((name) => `https://${name}`),
    })
    loadCSS()
    expect(document.head.lastChild.href).toEqual('https://gist.css/')
  })
@ThaddeusJiang
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment