admin管理员组

文章数量:1287651

I have this method in a react ponent to load the Google Recaptcha API when ponentDidMount.

loadCaptcha = () => {
  ((d, s, id) => {
    const element = d.getElementsByTagName(s)[0];
    const fjs = element;
    let js = element;
    if (d.getElementById(id)) {
      return;
    }
    js = d.createElement(s);
    js.id = id;
    js.src = '//google/recaptcha/api.js';
    fjs.parentNode.insertBefore(js, fjs);
  })(document, 'script', 'google-recaptcha');
};

I'm having problems mocking document in a Jest test file because d has only Document { location: [Getter/Setter] } and, for that, the other objects are undefined.

I have tried adding setupFiles in Jest config, as other people said in another question:

"setupFiles": ["<rootDir>/__mocks__/documentMock.js"]

documentMock.js:

Object.defineProperty(document, 'currentScript', {
  value: document.createElement('script'),
});

But with no luck. Has someone fixed that?

Also tried this:

beforeAll(() => {
  global.document: { //code }
})

Pd: This is the error:

TypeError: Cannot read property 'parentNode' of undefined

Thanks.

I have this method in a react ponent to load the Google Recaptcha API when ponentDidMount.

loadCaptcha = () => {
  ((d, s, id) => {
    const element = d.getElementsByTagName(s)[0];
    const fjs = element;
    let js = element;
    if (d.getElementById(id)) {
      return;
    }
    js = d.createElement(s);
    js.id = id;
    js.src = '//google./recaptcha/api.js';
    fjs.parentNode.insertBefore(js, fjs);
  })(document, 'script', 'google-recaptcha');
};

I'm having problems mocking document in a Jest test file because d has only Document { location: [Getter/Setter] } and, for that, the other objects are undefined.

I have tried adding setupFiles in Jest config, as other people said in another question:

"setupFiles": ["<rootDir>/__mocks__/documentMock.js"]

documentMock.js:

Object.defineProperty(document, 'currentScript', {
  value: document.createElement('script'),
});

But with no luck. Has someone fixed that?

Also tried this:

beforeAll(() => {
  global.document: { //code }
})

Pd: This is the error:

TypeError: Cannot read property 'parentNode' of undefined

Thanks.

Share Improve this question asked Oct 9, 2017 at 10:43 Albert Olivé CorbellaAlbert Olivé Corbella 4,2097 gold badges51 silver badges67 bronze badges 1
  • you were close, just use JSDOM instead of trying to mock the dom manually :) – Patrick Lee Scott Commented May 31, 2018 at 16:07
Add a ment  | 

3 Answers 3

Reset to default 5

There is no need to manually mock JSDOM in Jest. It will be automatically mocked if you select default testEnvironment inside jest.config.js file which is:

testEnvironment: "jest-environment-jsdom",

If you would like to use some DOM features not implemented in JSDOM just mock them following official docs, e.g.

window.matchMedia = jest.fn().mockImplementation(query => {
  return {
    matches: false,
    media: query,
    onchange: null,
    addListener: jest.fn(),
    removeListener: jest.fn(),
  };
});

use setupFiles with jsdom:

__mocks__/client.js

import { JSDOM } from "jsdom"
const dom = new JSDOM()
global.document = dom.window.document
global.window = dom.window

Then in your jest config:

"setupFiles": [
  "./__mocks__/client.js"
],

I got here to specifically mock currentScript, and couldn't find the exact right answer.

This was the solution for me:

./setupTests.ts

// Mock current script to be able to spy on it
Object.defineProperty(document, 'currentScript', {
  configurable: true,
  get() {
    return document.createElement('script');
  },
});

testFile.spec.ts

describe('Test Suite', () => {
  afterEach(() => jest.clearAllMocks());

  it('should test byproduct of document.currentScript.src', () => {
    jest.spyOn(document, 'currentScript', 'get').mockReturnValue({ src: '' } as any);

    // ... run code
  });
});

本文标签: javascriptMock document in Jest test fileStack Overflow