简体   繁体   English

使用 Jest 监视或模拟 document.createElement

[英]Spy on or mock document.createElement using Jest

I need to test some code that creates an element on document that is assigned a URL and then clicked.我需要测试一些在文档上创建一个元素的代码,该元素分配了一个 URL,然后单击。

I am using Jest.我正在使用 Jest。

const link = document.createElement('a')

I gave up trying to mock document as I can't see a simple way to do it, although it would have been nice to mock out the click.我放弃了模拟文档的尝试,因为我看不到一种简单的方法来做到这一点,尽管模拟点击会很好。

I need to know that createElement happened, so I decided to create a spy:我需要知道createElement发生了,所以我决定创建一个间谍:

jest.spyOn(document, 'createElement')

For some reason the spy is breaking the test and I get the same error that I got when trying to mock document:出于某种原因,间谍破坏了测试,我得到了与尝试模拟文档时相同的错误:

Error:  TypeError: Cannot set property 'href' of undefined

The code below the document.createElement is: document.createElement下面的代码是:

link.href = url

Any ideas?有任何想法吗?

Here is the solution, I use node.js runtime environment for demo:这是解决方案,我使用 node.js 运行时环境进行演示:

class Link {
  private name: string;
  private _href: string = '';
  constructor(name) {
    this.name = name;
  }

  get href() {
    return this._href;
  }

  set href(url) {
    this._href = url;
  }
}

const document = {
  createElement(name) {
    return new Link(name);
  }
};

function createLink(url) {
  const link = document.createElement('a');
  link.href = url;
  return link;
}

export { createLink, document, Link };

Unit test:单元测试:

import { createLink, document, Link } from './';

describe('createLink', () => {
  it('t1', () => {
    const url = 'https://github.com/mrdulin';
    jest.spyOn(document, 'createElement').mockReturnValueOnce(new Link('mock link'));
    const link = createLink(url);
    expect(link).toBeInstanceOf(Link);
    expect(link.href).toBe(url);
  });
});

 PASS  src/stackoverflow/57088724/index.spec.ts
  createLink
    ✓ t1 (6ms)

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        2.451s, estimated 3s

While working on my latest open source project ( TabMerger ), I came up with a simpler solution and think it is much more intuitive and can help someone who is struggling.在从事我最新的开源项目 ( TabMerger ) 时,我想出了一个更简单的解决方案,并认为它更直观,可以帮助正在苦苦挣扎的人。 Also, it can be adapted according to your needs very easily.此外,它可以很容易地根据您的需要进行调整。

// function to test
function exportJSON() {
  chrome.storage.local.get("groups", (local) => {
    var group_blocks = local.groups;
    chrome.storage.sync.get("settings", (sync) => {
      group_blocks["settings"] = sync.settings;
 
      var dataStr = "data:text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(group_blocks, null, 2));
      
      // want to test all of below also!!
      var anchor = document.createElement("a");
      anchor.setAttribute("href", dataStr);
      anchor.setAttribute("download", AppHelper.outputFileName() + ".json");
      anchor.click();
      anchor.remove();
    });
  });
}

To test, I simply mock the return value of the document.createElement function to return an anchor object which can be spied on:为了测试,我简单地模拟了document.createElement函数的返回值以返回一个可以被监视的锚对象:

describe("exportJSON", () => {
  it("correctly exports a JSON file of the current configuration", () => {
    // ARRANGE
    // creates the anchor tag as an object
    function makeAnchor(target) {
      return {
        target,
        setAttribute: jest.fn((key, value) => (target[key] = value)),
        click: jest.fn(),
        remove: jest.fn(),
      };
    }
    
    // spy on the document.createElement and mock its return
    // also spy on each anchor function you want to test
    var anchor = makeAnchor({ href: "#", download: "" });
    var createElementMock = jest.spyOn(document, "createElement").mockReturnValue(anchor);
    var setAttributeSpy = jest.spyOn(anchor, "setAttribute");
    var clickSpy = jest.spyOn(anchor, "click");
    var removeSpy = jest.spyOn(anchor, "remove");
     
    // create expectations
    var group_blocks = JSON.parse(localStorage.getItem("groups"));
    group_blocks["settings"] = JSON.parse(sessionStorage.getItem("settings"));
    const dataStr = "data:text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(group_blocks, null, 2));

    jest.clearAllMocks(); // start with clean mocks/spies before call is made
    
    // ACT
    AppFunc.exportJSON();
    
    // ASSERT
    // chromeLocalGetSpy, chromeSyncGetSpy defined elsewhere as
    // jest.spyOn(chrome.storage.local, "get") & jest.spyOn(chrome.storage.sync, "get"), respectively.
    expect(chromeLocalGetSpy).toHaveBeenCalledTimes(1);
    expect(chromeLocalGetSpy).toHaveBeenCalledWith("groups", anything);

    expect(chromeSyncGetSpy).toHaveBeenCalledTimes(1);
    expect(chromeSyncGetSpy).toHaveBeenCalledWith("settings", anything);

    expect(document.createElement).toHaveBeenCalledTimes(1);
    expect(document.createElement).toHaveBeenCalledWith("a");

    expect(setAttributeSpy).toHaveBeenCalledTimes(2);
    expect(setAttributeSpy).toHaveBeenNthCalledWith(1, "href", dataStr);
    expect(setAttributeSpy).toHaveBeenNthCalledWith(2, "download", AppHelper.outputFileName() + ".json");

    expect(clickSpy).toHaveBeenCalledTimes(1);
    expect(removeSpy).toHaveBeenCalledTimes(1);

    createElementMock.mockRestore(); // restore document.createElement so that it is unchanged in other tests
  });
});

Result结果

exportJSON
    √ correctly exports a JSON file of the current configuration (48 ms)

Code代码

Full code is available on my GitHub完整代码可在我的GitHub 上找到

You can see that localStorage & sessionStorage are used to mock the chrome.storage.local & chrome.storage.sync API, respectively, in the <rootDir>/tests/__mocks__/chromeMock.js folder.<rootDir>/tests/__mocks__/chromeMock.js文件夹中,您可以看到localStoragesessionStorage分别用于模拟chrome.storage.localchrome.storage.sync API。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM