summaryrefslogtreecommitdiff
path: root/spec/frontend/vue_shared/components/source_viewer_spec.js
blob: 758068379de2256fe6d26d4e43e7bc6def86c54f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
import hljs from 'highlight.js/lib/core';
import { shallowMountExtended } from 'helpers/vue_test_utils_helper';
import SourceViewer from '~/vue_shared/components/source_viewer.vue';
import LineNumbers from '~/vue_shared/components/line_numbers.vue';
import waitForPromises from 'helpers/wait_for_promises';

jest.mock('highlight.js/lib/core');

describe('Source Viewer component', () => {
  let wrapper;
  const content = `// Some source code`;
  const highlightedContent = `<span data-testid='test-highlighted'>${content}</span>`;
  const language = 'javascript';

  hljs.highlight.mockImplementation(() => ({ value: highlightedContent }));
  hljs.highlightAuto.mockImplementation(() => ({ value: highlightedContent }));

  const createComponent = async (props = {}) => {
    wrapper = shallowMountExtended(SourceViewer, { propsData: { content, language, ...props } });
    await waitForPromises();
  };

  const findLineNumbers = () => wrapper.findComponent(LineNumbers);
  const findHighlightedContent = () => wrapper.findByTestId('test-highlighted');

  beforeEach(() => createComponent());

  afterEach(() => wrapper.destroy());

  describe('highlight.js', () => {
    it('registers the language definition', async () => {
      const languageDefinition = await import(`highlight.js/lib/languages/${language}`);

      expect(hljs.registerLanguage).toHaveBeenCalledWith(language, languageDefinition.default);
    });

    it('highlights the content', () => {
      expect(hljs.highlight).toHaveBeenCalledWith(content, { language });
    });

    describe('auto-detect enabled', () => {
      beforeEach(() => createComponent({ autoDetect: true }));

      it('highlights the content with auto-detection', () => {
        expect(hljs.highlightAuto).toHaveBeenCalledWith(content);
      });
    });
  });

  describe('rendering', () => {
    it('renders Line Numbers', () => {
      expect(findLineNumbers().props('lines')).toBe(1);
    });

    it('renders the highlighted content', () => {
      expect(findHighlightedContent().exists()).toBe(true);
    });
  });
});