'Expect an HTML element to be focused fails

Im doing a unit test for my component. It consists of 6 <input> elements, where the first input is set to be auto focused. I am trying to test this.

Here is my test code:

import React from 'react';
import { configure, shallow, ShallowWrapper } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';

import HCPinCode from './HCPinCode';

configure({ adapter: new Adapter() });

describe('<HCPinCode>', () => {
    let wrapper: ShallowWrapper;

    beforeEach(() => {
        wrapper = shallow(
            <HCPinCode
                length={6}
                hasFailed={false}
                codeChangeHandler={(_: string) => {}}
            ></HCPinCode>
        );
    });

    it('mounts without crashing', () => {
        wrapper.unmount();
    });

    it('should be rendered and first input element should be auto-focused', () => {
        const inputElement = wrapper.find('input:first-child').getElement();

        expect(document.activeElement).toBe(inputElement);
    });
});

When I run the unit test I get failure:

● <HCPinCode> › should be rendered and first input element should be auto-focused

    expect(received).toBe(expected) // Object.is equality

    - Expected  - 7
    + Received  + 1

    - <input
    -   autoFocus={true}
    -   className="field"
    -   onKeyDown={[Function onKeyDown]}
    -   onPaste={[Function onPaste]}
    -   value=""
    - />
    + <body />

basically it recognized the focused one as the body.

This is the component itself:

  return (
    <div className={containerClasses} ref={containerRef}>
      {codeState.map((codeValue, index) => (
        <input
          key={index}
          autoFocus={index === 0}
          className={fieldClasses}
          value={codeValue}
          onKeyDown={({ key }) => onKeyDown(key, index)}
          onPaste={(e) => onPaste(e, index)}
        />
      ))}
    </div>

codeState is just an array of numbers.

Also I console log the HTML tree built:

it('should be rendered and first input element should be auto-focused', () => {
    const inputElement = wrapper.find('input:first-child').getElement();

    console.log(wrapper.html());

    expect(document.activeElement).toBe(inputElement);
});

The log I get in console:

<div class="container"><input autofocus="" class="field" value=""/><input class="field" value=""/><input class="field" value=""/><input class="field" value=""/><input class="field" value=""/><input class="field" value=""/></div>

Indeed my first element has autofocus attribute.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source