Search code examples
mockingjestjsreact-test-rendererreact-bootstrap-typeahead

React-bootstrap Typeahead does not work with Jest snapshots


I have a very simple AsyncTypeahead example from the API documentation :

    import {AsyncTypeahead} from "react-bootstrap-typeahead";
    import React, {Component} from "react";

    class AsyncTest extends Component<Props, State> {
        constructor() {
            super()
            this.state = {
                isLoading:false,
                options:{}
            }
        }
        render() {
            return <AsyncTypeahead
                disabled={true}
                isLoading={this.state.isLoading}
                onSearch={query => {
                    this.setState({isLoading: true});
                    fetch(`https://api.github.com/search/users?q=123`)
                        .then(resp => resp.json())
                        .then(json => this.setState({
                            isLoading: false,
                            options: json.items,
                        }));
                }}
                options={this.state.options}
            />
        }
    }

export default AsyncTest;

Now if I want to create a Jest snapshot test of this component then I would write something like this :

import React from 'react';
import renderer from "react-test-renderer";
import AsyncTest from "./AsyncTest";

describe('Async Test', () => {
    test('test', () => {
        const test= <AsyncTest/>
        expect(renderer.create(test).toJSON()).toMatchSnapshot();
    });
});

This does not work. I get this error :

TypeError: Cannot read property 'style' of null

at Window.getComputedStyle (A:\frontend\node_modules\jest-environment-jsdom\node_modules\jsdom\lib\jsdom\browser\Window.js:524:20)
at copyStyles (A:\frontend\node_modules\react-bootstrap-typeahead\lib\containers\hintContainer.js:61:27)
at HintedInput.componentDidMount (A:\frontend\node_modules\react-bootstrap-typeahead\lib\containers\hintContainer.js:113:9)
at commitLifeCycles (A:\frontend\node_modules\react-test-renderer\cjs\react-test-renderer.development.js:10930:22)

Is this a known issue with bootstrap typeahead?


Solution

  • Had the same problem and this was my solution. Culprit is the Hintcontainer of typeahead and specifically this function:

    function copyStyles(inputNode, hintNode) {
      var inputStyle = window.getComputedStyle(inputNode);
      /* eslint-disable no-param-reassign */
    
      hintNode.style.borderStyle = interpolateStyle(inputStyle, 'border', 'style');
      hintNode.style.borderWidth = interpolateStyle(inputStyle, 'border', 'width');
      hintNode.style.fontSize = inputStyle.fontSize;
      hintNode.style.lineHeight = inputStyle.lineHeight;
      hintNode.style.margin = interpolateStyle(inputStyle, 'margin');
      hintNode.style.padding = interpolateStyle(inputStyle, 'padding');
      /* eslint-enable no-param-reassign */
    }
    

    Problem with createMockNode: Styles from the inputNode are not a common object, but a CSSStyleDeclaration, and I did not bother to mock this completely.
    https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleDeclaration

    So, using window.getComputedStyle does not work when swapped out with a common object. Most simple solution to me, was to mock window.getComputedStyle, too. So, First part is to mock the getComputedStyle function which is triggering the error.

    global.window.getComputedStyle = jest.fn(x=>({}));
    

    But createNodeMock is still needed to provide an empty style object for the input node.

    TLDR; Snapshots work with this snippet

       global.window.getComputedStyle = jest.fn(x=>({}));
            const createNodeMock = (element) => ({
                    style: {},
            });
       const options={createNodeMock};
       const tree = renderer
                .create(form,options)
                .toJSON();