// @flow
import type { Node } from 'react';
import axe from 'axe-core';
import { mountWrappedComponent } from './renderer';

let documentWrapper;
export const mountToDocument = (jsx: Node) => {
  if (!documentWrapper) {
    documentWrapper = global.document.createElement('main');
    global.document.body.appendChild(documentWrapper);
  }

  const container = mountWrappedComponent(jsx);
  documentWrapper.innerHTML = '';
  documentWrapper.appendChild(container.getDOMNode());

  return container;
};

const axeConfig = {
  rules: {
    'color-contrast': { enabled: false },
  },
};

export const auditAccessibility = async (componentDomNode: HTMLElement) => {
  return axe.run(componentDomNode, axeConfig);
};

/**
 * Tests if a component is W3C compliant
 */
export const itIsAccessible = (jsx: Node) => {
  it('passes the accessiblity audit', async () => {
    const component = mountToDocument(jsx);
    const { violations } = await auditAccessibility(component.getDOMNode());
    expect(violations).toHaveLength(0);
  });
};
