text: import Vue, { nextTick } from 'vue';
  import VueApollo from 'vue-apollo';
  import MockAdapter from 'axios-mock-adapter';
  import * as Sentry from '@sentry/browser';
  import { GlLink, GlIcon, GlSkeletonLoader } from '@gitlab/ui';
  import axios from '~/lib/utils/axios_utils';
  import httpStatus from '~/lib/utils/http_status';
  import { mockTracking, unmockTracking } from 'helpers/tracking_helper';
  
  import VulnerabilityTraining, {
    i18n,
    mockProvider,
  } from 'ee/vulnerabilities/components/vulnerability_training.vue';
  import securityTrainingProvidersQuery from '~/security_configuration/graphql/security_training_providers.query.graphql';
  import { shallowMountExtended } from 'helpers/vue_test_utils_helper';
  import { SUPPORTED_IDENTIFIER_TYPES } from 'ee/vulnerabilities/constants';
  import {
    TRACK_CLICK_TRAINING_LINK_ACTION,
    TRACK_TRAINING_LOADED_ACTION,
  } from '~/security_configuration/constants';
  import createMockApollo from 'helpers/mock_apollo_helper';
  import waitForPromises from 'helpers/wait_for_promises';
  import {
    securityTrainingProvidersResponse,
    disabledSecurityTrainingProvidersResponse,
  } from 'jest/security_configuration/mock_data';
  
  const defaultProps = {
    identifiers: [
      { externalType: SUPPORTED_IDENTIFIER_TYPES.cwe, name: 'CWE-81' },
      { externalType: 'cve' },
    ],
  };
  
  const mockSuccessTrainingUrl = 'training/path';
  
  Vue.use(VueApollo);
  
  describe('VulnerabilityTraining component', () => {
    let wrapper;
    let apolloProvider;
    let mock;
  
    const createApolloProvider = ({ queryHandler } = {}) => {
      apolloProvider = createMockApollo([
        [
          securityTrainingProvidersQuery,
          queryHandler || jest.fn().mockResolvedValue(securityTrainingProvidersResponse),
        ],
      ]);
    };
  
    const createComponent = (props = {}, { slots = {}, secureVulnerabilityTraining = true } = {}) => {
      wrapper = shallowMountExtended(VulnerabilityTraining, {
        propsData: {
          ...defaultProps,
          ...props,
        },
        slots,
        apolloProvider,
        provide: {
          projectFullPath: 'namespace/project',
          glFeatures: {
            secureVulnerabilityTraining,
          },
        },
      });
    };
  
    beforeEach(async () => {
      mock = new MockAdapter(axios);
      createApolloProvider();
    });
  
    afterEach(() => {
      wrapper.destroy();
      apolloProvider = null;
      mock.restore();
    });
  
    const delayTrainingResponse = async () =>
      mock.onGet(mockProvider.path).reply(() => new Promise(() => {}));
    const mockTrainingSuccess = async () =>
      mock.onGet(mockProvider.path).reply(httpStatus.OK, { url: mockSuccessTrainingUrl });
    const waitForQueryToBeLoaded = () => waitForPromises();
    const findDescription = () => wrapper.findByTestId('description');
    const findUnavailableMessage = () => wrapper.findByTestId('unavailable-message');
    const findTrainingItemName = () => wrapper.findByText(mockProvider.name);
    const findTrainingItemLink = () => wrapper.findComponent(GlLink);
    const findTrainingItemLinkIcon = () => wrapper.findComponent(GlIcon);
  
    describe('with the query being successful', () => {
      describe('basic structure', () => {
        it('displays the description', async () => {
          createApolloProvider();
          createComponent();
          await waitForQueryToBeLoaded();
          expect(findDescription().text()).toBe(i18n.trainingDescription);
        });
  
        it('does not render component when there are no identifiers', () => {
          createApolloProvider();
          createComponent({ identifiers: [] });
          expect(wrapper.html()).toBeFalsy();
        });
  
        it('does not render component when there are no enabled securityTrainingProviders', async () => {
          createApolloProvider({
            queryHandler: jest.fn().mockResolvedValue(disabledSecurityTrainingProvidersResponse),
          });
          createComponent();
          await waitForQueryToBeLoaded();
  
          expect(wrapper.html()).toBeFalsy();
        });
  
        it('watches showVulnerabilityTraining and emits change', async () => {
          createApolloProvider();
          createComponent();
  
          await waitForQueryToBeLoaded();
          await nextTick();
  
          // Note: the event emits twice - the second time is when the query is loaded
          expect(wrapper.emitted('show-vulnerability-training')).toEqual([[false], [true]]);
        });
      });
  
      describe('with title slot', () => {
        it('renders slot content', async () => {
          const mockSlotText = 'some title';
          createComponent({}, { slots: { header: mockSlotText } });
          await waitForQueryToBeLoaded();
          expect(wrapper.text()).toContain(mockSlotText);
        });
      });
  
      describe('training availability message', () => {
        it('displays the message', async () => {
          createComponent({
            identifiers: [{ externalType: 'not supported identifier' }],
          });
          await waitForQueryToBeLoaded();
          expect(findUnavailableMessage().text()).toBe(i18n.trainingUnavailable);
        });
  
        it.each`
          identifier                                      | exists
          ${'not supported identifier'}                   | ${true}
          ${SUPPORTED_IDENTIFIER_TYPES.cwe.toUpperCase()} | ${false}
          ${SUPPORTED_IDENTIFIER_TYPES.cwe.toLowerCase()} | ${false}
        `('sets it to "$exists" for "$identifier"', async ({ identifier, exists }) => {
          await mockTrainingSuccess();
          createComponent({ identifiers: [{ externalType: identifier }] });
          await waitForQueryToBeLoaded();
          expect(findUnavailableMessage().exists()).toBe(exists);
        });
      });
  
      describe('training item', () => {
        it('displays GlSkeletonLoader when loading', async () => {
          await delayTrainingResponse();
          createComponent();
          await waitForQueryToBeLoaded();
  
          expect(wrapper.findComponent(GlSkeletonLoader).exists()).toBe(true);
        });
  
        it('displays training item information', async () => {
          await mockTrainingSuccess();
          createComponent();
          await waitForQueryToBeLoaded();
  
          expect(findTrainingItemName().exists()).toBe(true);
          expect(findTrainingItemLink().attributes('href')).toBe(mockSuccessTrainingUrl);
          expect(findTrainingItemLinkIcon().attributes('name')).toBe('external-link');
        });
  
        it('does not display training item information for non supported identifier', async () => {
          await mockTrainingSuccess();
          createComponent({ identifiers: [{ externalType: 'not supported identifier' }] });
          await waitForQueryToBeLoaded();
  
          expect(findTrainingItemName().exists()).toBe(false);
          expect(findTrainingItemLink().exists()).toBe(false);
          expect(findTrainingItemLinkIcon().exists()).toBe(false);
        });
      });
    });
  
    describe('with the query resulting in an error', () => {
      beforeEach(() => {
        jest.spyOn(Sentry, 'captureException');
        createApolloProvider({ queryHandler: jest.fn().mockResolvedValue(new Error()) });
        createComponent();
      });
  
      it('reports the error to sentry', async () => {
        expect(Sentry.captureException).not.toHaveBeenCalled();
  
        await waitForQueryToBeLoaded();
  
        expect(Sentry.captureException).toHaveBeenCalled();
      });
    });
  
    describe('metrics', () => {
      let trackingSpy;
  
      beforeEach(async () => {
        trackingSpy = mockTracking(undefined, wrapper.element, jest.spyOn);
        await mockTrainingSuccess();
        createComponent();
        await waitForQueryToBeLoaded();
      });
  
      afterEach(() => {
        unmockTracking();
      });
  
      const expectedTrackingOptions = {
        property: defaultProps.identifiers[0].name,
        label: `vendor_${mockProvider.id}`,
      };
  
      it('tracks when the training link gets loaded', () => {
        expect(trackingSpy).toHaveBeenCalledWith(
          undefined,
          TRACK_TRAINING_LOADED_ACTION,
          expectedTrackingOptions,
        );
      });
  
      it('tracks when a training link gets clicked', async () => {
        await findTrainingItemLink().vm.$emit('click');
  
        expect(trackingSpy).toHaveBeenCalledWith(
          undefined,
          TRACK_CLICK_TRAINING_LINK_ACTION,
          expectedTrackingOptions,
        );
      });
    });
  
    describe('when secureVulnerabilityTraining feature flag is disabled', () => {
      it('does not render the VulnerabilityTraining component', () => {
        createComponent({}, { secureVulnerabilityTraining: false });
        expect(wrapper.html()).toBeFalsy();
      });
    });
  });
  