import React from 'react';
import { mount } from 'enzyme';

import TutorialResponse from '.';
import CodeEditor from '@ui/compositions/CodeEditor';
import { PermissionContext } from '@ui/compositions/TutorialModal';

const getClientRectSpy = jest.fn(() => ({ width: 100 }));
Range.prototype.getBoundingClientRect = getClientRectSpy;
Range.prototype.getClientRects = getClientRectSpy;

describe('TutorialResponse', () => {
  let node;
  let props;

  beforeEach(() => {
    props = {
      snippet: {
        response: 'console.log("Response here")',
      },
      updateTutorial: jest.fn(),
    };

    node = mount(
      <PermissionContext.Provider value={false}>
        <TutorialResponse {...props} />
      </PermissionContext.Provider>
    );
  });

  it('should display tutorial response editor', () => {
    expect(node.find(CodeEditor)).toHaveLength(1);
  });

  it('should disable options when readOnly', () => {
    const readOnlyNode = mount(
      <PermissionContext.Provider value={true}>
        <TutorialResponse {...props} />
      </PermissionContext.Provider>
    );

    const options = readOnlyNode.find(CodeEditor).props().options;
    expect(options.readOnly).toStrictEqual('nocursor');
  });

  it('should call updateTutorial when the response is changed', () => {
    const cm = node.find(CodeEditor);
    const cmProps = cm.props();

    cmProps.onChange(cm, { origin: '+input' }, '{success: true}');
    expect(props.updateTutorial).toHaveBeenCalled();
  });

  it('should NOT call updateTutorial when origin prop is invalid', () => {
    const cm = node.find(CodeEditor);
    const cmProps = cm.props();

    cmProps.onChange(cm, { origin: '' }, '{success: true}');
    expect(props.updateTutorial).toHaveBeenCalledTimes(0);
  });
});
