Welcome to mirror list, hosted at ThFree Co, Russian Federation.

vue_test_utils_helper.js « __helpers__ « frontend « spec - gitlab.com/gitlab-org/gitlab-foss.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 20a79fc4d2f1cf189f502e480c9cd5cbe4b67090 (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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
import * as testingLibrary from '@testing-library/dom';
import {
  createWrapper,
  Wrapper, // eslint-disable-line no-unused-vars
  ErrorWrapper,
  mount,
  shallowMount,
  WrapperArray,
} from '@vue/test-utils';
import { compose } from 'lodash/fp';

const vNodeContainsText = (vnode, text) =>
  (vnode.text && vnode.text.includes(text)) ||
  (vnode.children && vnode.children.filter((child) => vNodeContainsText(child, text)).length);

/**
 * Create a VTU wrapper from an element.
 *
 * If a Vue instance manages the element, the wrapper is created
 * with that Vue instance.
 *
 * @param {HTMLElement} element
 * @param {Object} options
 * @returns {Wrapper} VTU wrapper
 */
const createWrapperFromElement = (element, options) =>
  // eslint-disable-next-line no-underscore-dangle
  createWrapper(element.__vue__ || element, options || {});

/**
 * Determines whether a `shallowMount` Wrapper contains text
 * within one of it's slots. This will also work on Wrappers
 * acquired with `find()`, but only if it's parent Wrapper
 * was shallowMounted.
 * NOTE: Prefer checking the rendered output of a component
 * wherever possible using something like `text()` instead.
 * @param {Wrapper} shallowWrapper - Vue test utils wrapper (shallowMounted)
 * @param {String} slotName
 * @param {String} text
 */
export const shallowWrapperContainsSlotText = (shallowWrapper, slotName, text) =>
  Boolean(
    shallowWrapper.vm.$slots[slotName].filter((vnode) => vNodeContainsText(vnode, text)).length,
  );

/**
 * Returns a promise that waits for a mutation to be fired before resolving
 * NOTE: There's no reject action here so it will hang if it waits for a mutation that won't happen.
 * @param {Object} store - The Vue store that contains the mutations
 * @param {String} expectedMutationType - The Mutation to wait for
 */
export const waitForMutation = (store, expectedMutationType) =>
  new Promise((resolve) => {
    const unsubscribe = store.subscribe((mutation) => {
      if (mutation.type === expectedMutationType) {
        unsubscribe();
        resolve();
      }
    });
  });

/**
 * Query function type
 * @callback FindFunction
 * @param text
 * @returns {Wrapper}
 */

/**
 * Query all function type
 * @callback FindAllFunction
 * @param text
 * @returns {WrapperArray}
 */

/**
 * Query find with options functions type
 * @callback FindWithOptionsFunction
 * @param text
 * @param options
 * @returns {Wrapper}
 */

/**
 * Query find all with options functions type
 * @callback FindAllWithOptionsFunction
 * @param text
 * @param options
 * @returns {WrapperArray}
 */

/**
 * Extended Wrapper queries
 * @typedef { {
 *   findByTestId: FindFunction,
 *   findAllByTestId: FindAllFunction,
 *   findComponentByTestId: FindFunction,
 *   findAllComponentsByTestId: FindAllFunction,
 *   findByRole: FindWithOptionsFunction,
 *   findAllByRole: FindAllWithOptionsFunction,
 *   findByLabelText: FindWithOptionsFunction,
 *   findAllByLabelText: FindAllWithOptionsFunction,
 *   findByPlaceholderText: FindWithOptionsFunction,
 *   findAllByPlaceholderText: FindAllWithOptionsFunction,
 *   findByText: FindWithOptionsFunction,
 *   findAllByText: FindAllWithOptionsFunction,
 *   findByDisplayValue: FindWithOptionsFunction,
 *   findAllByDisplayValue: FindAllWithOptionsFunction,
 *   findByAltText: FindWithOptionsFunction,
 *   findAllByAltText: FindAllWithOptionsFunction,
 *   findByTitle: FindWithOptionsFunction,
 *   findAllByTitle: FindAllWithOptionsFunction
 * } } ExtendedQueries
 */

/**
 * Extended Wrapper
 * @typedef {(Wrapper & ExtendedQueries)} ExtendedWrapper
 */

/**
 * Creates a Wrapper {@link https://v1.test-utils.vuejs.org/api/wrapper/} with
 * Additional Queries {@link https://testing-library.com/docs/queries/about}.
 * @param { Wrapper } wrapper
 * @returns { ExtendedWrapper }
 */
export const extendedWrapper = (wrapper) => {
  // https://testing-library.com/docs/queries/about
  const AVAILABLE_QUERIES = [
    'ByRole',
    'ByLabelText',
    'ByPlaceholderText',
    'ByText',
    'ByDisplayValue',
    'ByAltText',
    'ByTitle',
  ];

  if (Array.isArray(wrapper) || !wrapper?.find) {
    // eslint-disable-next-line no-console
    console.warn(
      '[vue-test-utils-helper]: you are trying to extend an object that is not a VueWrapper.',
    );
    return wrapper;
  }

  return Object.defineProperties(wrapper, {
    findByTestId: {
      /** @this { Wrapper } */
      value(id) {
        return this.find(`[data-testid="${id}"]`);
      },
    },
    findAllByTestId: {
      /** @this { Wrapper } */
      value(id) {
        return this.findAll(`[data-testid="${id}"]`);
      },
    },
    /*
     * Keep in mind that there are some limitations when using `findComponent`
     * with CSS selectors: https://v1.test-utils.vuejs.org/api/wrapper/#findcomponent
     */
    findComponentByTestId: {
      /** @this { Wrapper } */
      value(id) {
        return this.findComponent(`[data-testid="${id}"]`);
      },
    },
    /*
     * Keep in mind that there are some limitations when using `findAllComponents`
     * with CSS selectors: https://v1.test-utils.vuejs.org/api/wrapper/#findallcomponents
     */
    findAllComponentsByTestId: {
      /** @this { Wrapper } */
      value(id) {
        return this.findAllComponents(`[data-testid="${id}"]`);
      },
    },
    // `findBy`
    ...AVAILABLE_QUERIES.reduce((accumulator, query) => {
      return {
        ...accumulator,
        [`find${query}`]: {
          /** @this { Wrapper } */
          value(text, options = {}) {
            const elements = testingLibrary[`queryAll${query}`](this.element, text, options);

            // Element not found, return an `ErrorWrapper`
            if (!elements.length) {
              return new ErrorWrapper(query);
            }
            return createWrapperFromElement(elements[0], this.options);
          },
        },
      };
    }, {}),
    // `findAllBy`
    ...AVAILABLE_QUERIES.reduce((accumulator, query) => {
      return {
        ...accumulator,
        [`findAll${query}`]: {
          /** @this { Wrapper } */
          value(text, options = {}) {
            const elements = testingLibrary[`queryAll${query}`](this.element, text, options);

            const wrappers = elements.map((element) => {
              const elementWrapper = createWrapperFromElement(element, this.options);
              elementWrapper.selector = text;

              return elementWrapper;
            });

            const wrapperArray = new WrapperArray(wrappers);
            wrapperArray.selector = text;

            return wrapperArray;
          },
        },
      };
    }, {}),
  });
};

export const shallowMountExtended = compose(extendedWrapper, shallowMount);
export const mountExtended = compose(extendedWrapper, mount);