Jest mock script tag before import

Viewed 16

I know that directly get document element from the component isn't good idea , anyway for example I have SomeComponent jsx file imported like

import SomeComponent from '../components/SomeComponent';

export default MyComponent = () => {
  return (
    SomeComponent.test ? "Hey" : "not Hey"
  )
}

inside of that component I have , element is a script with some content

const el = document.getElementById('element');
const json = el && el.innerText;
const info = json && JSON.parse(json);
export default test = info.someKey

Unit tests for MyComponent is something like this

describe('Tests for MyComponent', () => {
  it('should render without any problem', () => {
    wrapper = shallow(<MyComponent />);
    expect(wrapper).toExist();
  });
});

it failed with TypeError: Cannot read property 'someKey' of null

How can I mock SomeComponent script tag with innerText

1 Answers

It works when I mocked it on the setupTests.js file

const el = document.createElement('script');
el.setAttribute('id', 'el');
el.innerText = mock;
document.head.append(el);
Related