import childrenFromHtml from './childrenFromHtml';
import { children } from './gutenberg';

jest.mock('./gutenberg');

describe('childrenFromHtml function', () => {
  /**
   * Fixture: example HTML that this function should parse
   */
  const HTML_FIXTURE = 'Test <strong>text</strong>';

  /**
   * Backup of `document.createElement`
   * We swap this with a mock for these tests and need to restore it afterwards.
   * @type {function}
   */
  const createElementBackup = document.createElement;

  /**
   * Sets up global state for tests:
   *  - swaps `document.createElement` for a mock function
   */
  beforeAll(() => {
    document.createElement = jest.fn();
  });

  /**
   * Resets the `document.createElement` mock each run
   * Set the mock up so the test function should be able to run to completion.
   */
  beforeEach(() => {
    document.createElement.mockReturnValue({ childNodes: 'test nodes' });
  });

  /**
   * Restores `document.createElement` after tests finish
   */
  afterAll(() => {
    document.createElement = createElementBackup;
  });

  it('creates an HTML element', () => {
    document.createElement.mockClear();

    childrenFromHtml(HTML_FIXTURE);

    expect(document.createElement).toHaveBeenCalled();
    expect(document.createElement).toHaveBeenCalledWith('div');
  });

  it('assigns the provided HTML to the element', () => {
    const element = { };
    document.createElement.mockReturnValue(element);

    childrenFromHtml(HTML_FIXTURE);

    expect(element.innerHTML).toBe(HTML_FIXTURE);
  });

  it("passes the element to Gutenberg's fromDOM", () => {
    children.fromDOM.mockClear();

    childrenFromHtml(HTML_FIXTURE);

    expect(children.fromDOM).toHaveBeenCalled();
    expect(children.fromDOM).toHaveBeenCalledWith('test nodes');
  });

  it('returns the converted result', () => {
    children.fromDOM.mockReturnValue('mock result');
    expect(childrenFromHtml(HTML_FIXTURE)).toBe('mock result');
  });
});
