@leaflink/dom-testing-utils 0.0.0-PR-14--3ff9079

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,219 @@
1
+ # @leaflink/dom-testing-utils
2
+
3
+ > Leaflink repository to manage test utilities to be shared across front-end applications.
4
+
5
+ [![version](https://img.shields.io/npm/v/@leaflink/dom-testing-utils.svg)](http://npm.im/@leaflink/dom-testing-utils)
6
+ [![downloads](https://img.shields.io/npm/dm/@leaflink/dom-testing-utils.svg)](http://npm-stat.com/charts.html?package=@leaflink/dom-testing-utils&from=2015-08-01)
7
+ [![MIT License](https://img.shields.io/npm/l/@leaflink/dom-testing-utils.svg)](http://opensource.org/licenses/MIT)
8
+ [![semantic-release](https://img.shields.io/badge/%20%20%F0%9F%93%A6%F0%9F%9A%80-semantic--release-e10079.svg)](https://github.com/semantic-release/semantic-release)
9
+ [![Commitizen friendly](https://img.shields.io/badge/commitizen-friendly-brightgreen.svg)](http://commitizen.github.io/cz-cli/)
10
+
11
+ <!-- START doctoc generated TOC please keep comment here to allow auto update -->
12
+ <!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->
13
+
14
+ - [Installation](#installation)
15
+ - [Usage](#usage)
16
+ - [Global setup](#global-setup)
17
+ - [Setup file](#setup-file)
18
+ - [`cleanupNoty`](#cleanupnoty)
19
+ - [`waitForLoadingToFinish`](#waitforloadingtofinish)
20
+ - [`cleanupDropdowns`](#cleanupdropdowns)
21
+ - [`assertAndDismissNoty`](#assertanddismissnoty)
22
+ - [`createFixtureGenerator`](#createfixturegenerator)
23
+ - [Mocking API Endpoints](#mocking-api-endpoints)
24
+
25
+ <!-- END doctoc generated TOC please keep comment here to allow auto update -->
26
+
27
+ ## Installation
28
+
29
+ ```sh
30
+ npm install --save-dev @leaflink/dom-testing-utils
31
+ ```
32
+
33
+ ## Usage
34
+
35
+ In your `*.spec.(ts|js)` files you can import utility functions.
36
+
37
+ ```ts
38
+ import {
39
+ waitForLoadingToFinish,
40
+ cleanupDropdowns,
41
+ assertAndDismissNoty,
42
+ cleanupNoty,
43
+ createFixtureGenerator,
44
+ } from '@leaflink/dom-testing-utils';
45
+
46
+ it('...', () => {
47
+ cleanupNoty();
48
+ });
49
+ ```
50
+
51
+ There's also shared setup files you can extend from.
52
+
53
+ ### Global setup
54
+
55
+ Add the following line to your `vite.config.js`:
56
+
57
+ ```js
58
+ globalSetup: 'node_modules/@leaflink/dom-testing-utils/dist/global-setup.js',
59
+ ```
60
+
61
+ This will run once *before everything*. See <https://vitest.dev/config/#globalsetup>.
62
+
63
+ ### Setup file
64
+
65
+ Add the following line to your `vite.config.js`:
66
+
67
+ ```js
68
+ setupFiles: ['node_modules/@leaflink/dom-testing-utils/dist/setup-env.js'],
69
+ ```
70
+
71
+ This will be run once before *each* test file. See <https://vitest.dev/config/#setupfiles>.
72
+
73
+ ### `cleanupNoty`
74
+
75
+ Helper method to remove all noty alerts from the DOM.
76
+
77
+ **Parameters**: None
78
+
79
+ **Returns**: `void`
80
+
81
+ ### `waitForLoadingToFinish`
82
+
83
+ Utility to wait for loading to complete. Need to add a `data-test` to any loading elements. Defaults to `ll-loading` **or** `loading-spinner` if `testId` is not specified.
84
+
85
+ | **Parameters** | **Type** | **Default** | **Summary** |
86
+ | ----------- | ----------- | ----------- |----------- |
87
+ | testId | `string` | `ll-loading` && `loading-spinner` |The data test ID to target. |
88
+
89
+ **Returns**: `Promise<boolean>`
90
+
91
+ Will resolve or throw if the loaders stay in the DOM.
92
+
93
+ ### `cleanupDropdowns`
94
+
95
+ Helper method to remove all floating Stash Dropdown elements from the DOM.
96
+
97
+ **Parameters**: None
98
+
99
+ **Returns**: `void`
100
+
101
+ ### `assertAndDismissNoty`
102
+
103
+ Helper to assert and manually dismiss a notification. This is useful in scenarios where cleanupNoty() does not work as expected, such as when validating error messages in test suites.
104
+
105
+ | **Parameters** | **Type** | **Default** | **Summary** |
106
+ | ----------- | ----------- | ----------- |----------- |
107
+ | text | `string` | *Required* | Expected notification text. |
108
+
109
+ **Returns**: `void`
110
+
111
+ ### `createFixtureGenerator`
112
+
113
+ Higher order function that takes a method whose responsibility is to create a **single** data fixture object and returns a new generator function that allows you to create 1 or more of those fixtures. Fixture generator function that's returned supports passing optional `num` and `overrides` params.
114
+
115
+ | **Parameters** | **Type** | **Default** | **Summary** |
116
+ | ----------- | ----------- | ----------- |----------- |
117
+ | `fixtureFn` | `function` | *Required* | Method that generates and returns a single data object. |
118
+
119
+ **Returns**
120
+
121
+ ```ts
122
+ (num?, overrides?) => Array<{[key: string]: any}> | {[key: string]: any}
123
+ // OR
124
+ (overrides?) => {[key: string]: any}
125
+ ```
126
+
127
+ A new generator function that accepts a number & overrides where:
128
+
129
+ - `num` = The number of fake data objects to generate. Defaults to 1
130
+ - `overrides` = Specific attributes you want to override in each data fixture object.
131
+
132
+ When calling the returned function, you'll get an array OR object of fixture data (It will be a ** single object** if `num = 1`).
133
+
134
+ **Examples**
135
+
136
+ Quick example:
137
+
138
+ ```ts
139
+ const generateInvoice = (overrides) => ({ id: uuid(), balance: 15799, classification: "Adult Use", ...overrides});
140
+ const generateInvoices = createFixtureGenerator(generateInvoice);
141
+
142
+ generateInvoices()
143
+ // => Single invoice object
144
+
145
+ generateInvoices(1)
146
+ // => Single invoice object
147
+
148
+ generateInvoices(1, { foo: 'bar' })
149
+ // => Single invoice object, override `foo` to equal `'bar'`
150
+
151
+ generateInvoices({ foo: 'bar' })
152
+ // => Single invoice object, override `foo` to equal `'bar'`
153
+
154
+ generateInvoices(10)
155
+ // => Array of 10 invoice objects
156
+
157
+ generateInvoices(10, { foo: 'bar' })
158
+ // => Array of 10 invoice objects, override `foo` to equal `'bar'` in each
159
+ ```
160
+
161
+ Full example:
162
+
163
+ ```ts
164
+ // tests/fixtures/products.ts
165
+ import { faker } from '@faker-js/faker';
166
+ import { createFixtureGenerator } from '@leaflink/dom-testing-utils';
167
+
168
+ export const generateProduct = (overrides = {}) => ({
169
+ sku: git.commitSha(),
170
+ name: faker.commerce.productName(),
171
+ quantity: faker.random.number(100),
172
+ cases: faker.random.number(10),
173
+ ...overrides,
174
+ });
175
+
176
+ export default createFixtureGenerator(generateProduct);
177
+
178
+ // services/api/products.ts
179
+ import generateProducts from '@/tests/fixtures/products';
180
+
181
+ // ...
182
+ const mockProducts = generateProducts(10, { cases: 25 })
183
+ // ...
184
+ ```
185
+
186
+ ### Mocking API Endpoints
187
+
188
+ In order to mock API endpoints that your tests interact with, you can get a set of mocking functions from `createMockApiUtils`.
189
+
190
+ ```ts
191
+ import { createMockApiUtils } from '@leaflink/dom-testing-utils';
192
+ import yourServer from './server.ts';
193
+
194
+ const {
195
+ mockGetData,
196
+ mockGetEndpoint,
197
+ mockPatchData,
198
+ // etc.
199
+ } = createMockApiUtils(yourServer);
200
+ ```
201
+
202
+ There are two flavors of mocking utility functions:
203
+ 1. mock{VERB}Data - mocks response with a singular data object
204
+ 2. mock{VERB}Endpoint - mocks a response endpoint with a function like msw's [Response Resolver](https://mswjs.io/docs/getting-started/mocks/rest-api#response-resolver)
205
+
206
+ To mock an endpoint with simple return data
207
+ ```ts
208
+ mockGetData('/relative-url', myMockObj);
209
+ ```
210
+ or you can customize the response
211
+ ```ts
212
+ mockGetEndpoint('/relative-url', (req, res, ctx) => {
213
+ if (someConditional()) {
214
+ res(ctx.json(true));
215
+ } else {
216
+ res(ctx.json(false));
217
+ }
218
+ });
219
+ ```
@@ -0,0 +1 @@
1
+ export * from './mockEndpoints';
@@ -0,0 +1,2 @@
1
+ export * from './mockEndpoints';
2
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"src/","sources":["api/index.ts"],"names":[],"mappings":"AAAA,cAAc,iBAAiB,CAAC"}
@@ -0,0 +1,17 @@
1
+ import { DefaultRequestBody, RequestParams, ResponseResolver, rest, RestContext, RestRequest } from 'msw';
2
+ import { SetupServerApi } from 'msw/node';
3
+ export type RestMethod = keyof typeof rest;
4
+ export declare const createMockApiUtils: (server: SetupServerApi) => {
5
+ mockEndpointData: <ResponseBody extends DefaultRequestBody = any>(relativeUrl: string, responseData: ResponseBody, method: RestMethod) => void;
6
+ mockEndpoint: <RequestBodyType extends DefaultRequestBody = DefaultRequestBody, ResponseBody_1 extends DefaultRequestBody = any, Params extends RequestParams = RequestParams>(relativeUrl: string, responseCallback: ResponseResolver<RestRequest<RequestBodyType, Params>, RestContext, ResponseBody_1>, method: RestMethod) => void;
7
+ mockGetData: <ResponseBody_2 extends DefaultRequestBody = any>(relativeUrl: string, responseData: ResponseBody_2) => void;
8
+ mockPostData: <ResponseBody_2 extends DefaultRequestBody = any>(relativeUrl: string, responseData: ResponseBody_2) => void;
9
+ mockPutData: <ResponseBody_2 extends DefaultRequestBody = any>(relativeUrl: string, responseData: ResponseBody_2) => void;
10
+ mockDeleteData: <ResponseBody_2 extends DefaultRequestBody = any>(relativeUrl: string, responseData: ResponseBody_2) => void;
11
+ mockPatchData: <ResponseBody_2 extends DefaultRequestBody = any>(relativeUrl: string, responseData: ResponseBody_2) => void;
12
+ mockGetEndpoint: <RequestBodyType_1 extends DefaultRequestBody = DefaultRequestBody, ResponseBody_3 extends DefaultRequestBody = any, Params_1 extends RequestParams = RequestParams>(relativeUrl: string, responseCallback: ResponseResolver<RestRequest<RequestBodyType_1, Params_1>, RestContext, ResponseBody_3>) => void;
13
+ mockPostEndpoint: <RequestBodyType_1 extends DefaultRequestBody = DefaultRequestBody, ResponseBody_3 extends DefaultRequestBody = any, Params_1 extends RequestParams = RequestParams>(relativeUrl: string, responseCallback: ResponseResolver<RestRequest<RequestBodyType_1, Params_1>, RestContext, ResponseBody_3>) => void;
14
+ mockPutEndpoint: <RequestBodyType_1 extends DefaultRequestBody = DefaultRequestBody, ResponseBody_3 extends DefaultRequestBody = any, Params_1 extends RequestParams = RequestParams>(relativeUrl: string, responseCallback: ResponseResolver<RestRequest<RequestBodyType_1, Params_1>, RestContext, ResponseBody_3>) => void;
15
+ mockDeleteEndpoint: <RequestBodyType_1 extends DefaultRequestBody = DefaultRequestBody, ResponseBody_3 extends DefaultRequestBody = any, Params_1 extends RequestParams = RequestParams>(relativeUrl: string, responseCallback: ResponseResolver<RestRequest<RequestBodyType_1, Params_1>, RestContext, ResponseBody_3>) => void;
16
+ mockPatchEndpoint: <RequestBodyType_1 extends DefaultRequestBody = DefaultRequestBody, ResponseBody_3 extends DefaultRequestBody = any, Params_1 extends RequestParams = RequestParams>(relativeUrl: string, responseCallback: ResponseResolver<RestRequest<RequestBodyType_1, Params_1>, RestContext, ResponseBody_3>) => void;
17
+ };
@@ -0,0 +1,58 @@
1
+ import { rest, } from 'msw';
2
+ export const createMockApiUtils = (server) => {
3
+ /**
4
+ * Mock endpoint with data
5
+ */
6
+ const mockEndpointData = (relativeUrl, responseData, method) => {
7
+ server.use(rest[method](relativeUrl, (_req, res, ctx) => {
8
+ return res(ctx.json(responseData));
9
+ }));
10
+ };
11
+ /**
12
+ * Mock endpoint with a callback function
13
+ */
14
+ const mockEndpoint = (relativeUrl, responseCallback, method) => {
15
+ server.use(rest[method](relativeUrl, responseCallback));
16
+ };
17
+ /**
18
+ * Creates a function to mock an endpoint with data for a particular HTTP verb
19
+ * @param method - the verb to target this endpoint for
20
+ */
21
+ const createDataHelper = (method) => (relativeUrl, responseData) => {
22
+ return mockEndpointData(relativeUrl, responseData, method);
23
+ };
24
+ /**
25
+ * Creates a function to mock an endpoint with a callback function for a particular HTTP verb
26
+ * @param method - the verb to target this endpoint for
27
+ */
28
+ const createEndpointHelper = (method) => (relativeUrl, responseCallback) => {
29
+ return mockEndpoint(relativeUrl, responseCallback, method);
30
+ };
31
+ // #region Shortcut Functions
32
+ const mockGetData = createDataHelper('get');
33
+ const mockPostData = createDataHelper('post');
34
+ const mockPutData = createDataHelper('put');
35
+ const mockDeleteData = createDataHelper('delete');
36
+ const mockPatchData = createDataHelper('patch');
37
+ const mockGetEndpoint = createEndpointHelper('get');
38
+ const mockPostEndpoint = createEndpointHelper('post');
39
+ const mockPutEndpoint = createEndpointHelper('put');
40
+ const mockDeleteEndpoint = createEndpointHelper('delete');
41
+ const mockPatchEndpoint = createEndpointHelper('patch');
42
+ // #endregion
43
+ return {
44
+ mockEndpointData,
45
+ mockEndpoint,
46
+ mockGetData,
47
+ mockPostData,
48
+ mockPutData,
49
+ mockDeleteData,
50
+ mockPatchData,
51
+ mockGetEndpoint,
52
+ mockPostEndpoint,
53
+ mockPutEndpoint,
54
+ mockDeleteEndpoint,
55
+ mockPatchEndpoint,
56
+ };
57
+ };
58
+ //# sourceMappingURL=mockEndpoints.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mockEndpoints.js","sourceRoot":"src/","sources":["api/mockEndpoints.ts"],"names":[],"mappings":"AAAA,OAAO,EAIL,IAAI,GAGL,MAAM,KAAK,CAAC;AAKb,MAAM,CAAC,MAAM,kBAAkB,GAAG,CAAC,MAAsB,EAAE,EAAE;IAC3D;;OAEG;IACH,MAAM,gBAAgB,GAAG,CACvB,WAAmB,EACnB,YAA0B,EAC1B,MAAkB,EAClB,EAAE;QACF,MAAM,CAAC,GAAG,CACR,IAAI,CAAC,MAAM,CAAC,CAAC,WAAW,EAAE,CAAC,IAAI,EAAE,GAAG,EAAE,GAAG,EAAE,EAAE;YAC3C,OAAO,GAAG,CAAC,GAAG,CAAC,IAAI,CAAC,YAAY,CAAC,CAAC,CAAC;QACrC,CAAC,CAAC,CACH,CAAC;IACJ,CAAC,CAAC;IAEF;;OAEG;IACH,MAAM,YAAY,GAAG,CAKnB,WAAmB,EACnB,gBAIC,EACD,MAAkB,EAClB,EAAE;QACF,MAAM,CAAC,GAAG,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,WAAW,EAAE,gBAAgB,CAAC,CAAC,CAAC;IAC1D,CAAC,CAAC;IAEF;;;OAGG;IACH,MAAM,gBAAgB,GACpB,CAAC,MAAkB,EAAE,EAAE,CACvB,CACE,WAAmB,EACnB,YAA0B,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@
1
+ {"version":3,"file":"global-setup.js","sourceRoot":"src/","sources":["global-setup.ts"],"names":[],"mappings":"AAAA,MAAM,CAAC,OAAO;IACZ,OAAO,CAAC,GAAG,CAAC,EAAE,GAAG,KAAK,CAAC;AACzB,CAAC"}
@@ -0,0 +1,50 @@
1
+ /**
2
+ * Utility to wait for loading to complete. Need to add a `data-test` to any
3
+ * loading elements. Defaults to `ll-loading` OR `loading-spinner` if test ID is not specified.
4
+ *
5
+ * @param {string} testId - The data test ID to target
6
+ * @returns {Promise<boolean>} - Will resolve or throw if the loaders stay in the DOM.
7
+ */
8
+ export declare function waitForLoadingToFinish(textMatch?: RegExp): Promise<void>;
9
+ /**
10
+ * Helper method to remove all noty alerts from the DOM.
11
+ *
12
+ * @returns void
13
+ */
14
+ export declare function cleanupNoty(): void;
15
+ export declare function cleanupDropdowns(): void;
16
+ /**
17
+ * Helper to assert and manually dismiss a notification. This is useful in scenarios where
18
+ * cleanupNoty() does not work as expected, such as when validating error messages in test suites
19
+ *
20
+ * @param {string | RegExp} text - expected notification text
21
+ *
22
+ * @returns void
23
+ */
24
+ export declare function assertAndDismissNoty(text: string): Promise<void>;
25
+ /**
26
+ * Higher order function that takes a method whose responsibility is to create a
27
+ * **single** data fixture object and returns a new generator function that
28
+ * allows you to create 1 or many of those fixtures. Fixture generator function
29
+ * that's returned supports passing optional `num` and `overrides` params.
30
+ *
31
+ * @example
32
+ *
33
+ * const generateInvoice = (overrides) => ({ id: uuid(), balance: 15799, classification: "Adult Use", ...overrides});
34
+ * const generateInvoices = createFixtureGenerator(generateInvoice);
35
+ *
36
+ * generateInvoices() // => Single invoice object
37
+ * generateInvoices(1) // => Single invoice object
38
+ * generateInvoices(1, { foo: 'bar' }) // => Single invoice object, override `foo` to equal `'bar'`
39
+ * generateInvoices({ foo: 'bar' }) // => Single invoice object, override `foo` to equal `'bar'`
40
+ * generateInvoices(10) // => Array of 10 invoice objects
41
+ * generateInvoices(10, { foo: 'bar' }) // => Array of 10 invoice objects, override `foo` to equal `'bar'` in each
42
+ *
43
+ * @param {function} fixtureFn - Method that generates a JSON data fixture.
44
+ * @returns {function}
45
+ * @returns {array|object} - Array of fixture objects or single object if n = 1.
46
+ */
47
+ export declare function createFixtureGenerator(fixtureFn: any): (num?: number | {
48
+ [key: string]: any;
49
+ }, overrides?: {}) => any;
50
+ export * from './api';
package/dist/index.js ADDED
@@ -0,0 +1,75 @@
1
+ import { screen, waitForElementToBeRemoved } from '@testing-library/vue';
2
+ import { default as userEvent } from '@testing-library/user-event';
3
+ /**
4
+ * Utility to wait for loading to complete. Need to add a `data-test` to any
5
+ * loading elements. Defaults to `ll-loading` OR `loading-spinner` if test ID is not specified.
6
+ *
7
+ * @param {string} testId - The data test ID to target
8
+ * @returns {Promise<boolean>} - Will resolve or throw if the loaders stay in the DOM.
9
+ */
10
+ export function waitForLoadingToFinish(textMatch = /ll\-loading|loading\-spinner/) {
11
+ return waitForElementToBeRemoved(() => [...screen.queryAllByTestId(textMatch)], { timeout: 2000 });
12
+ }
13
+ /**
14
+ * Helper method to remove all noty alerts from the DOM.
15
+ *
16
+ * @returns void
17
+ */
18
+ export function cleanupNoty() {
19
+ document
20
+ .querySelectorAll('.noty_bar')
21
+ .forEach((elem) => elem.parentNode?.removeChild(elem));
22
+ }
23
+ export function cleanupDropdowns() {
24
+ document
25
+ .querySelectorAll('.mount-point-container')
26
+ .forEach((elem) => elem.parentNode?.removeChild(elem));
27
+ }
28
+ /**
29
+ * Helper to assert and manually dismiss a notification. This is useful in scenarios where
30
+ * cleanupNoty() does not work as expected, such as when validating error messages in test suites
31
+ *
32
+ * @param {string | RegExp} text - expected notification text
33
+ *
34
+ * @returns void
35
+ */
36
+ export async function assertAndDismissNoty(text) {
37
+ const noty = await screen.findByText(text);
38
+ expect(noty).toBeInTheDocument();
39
+ await userEvent.click(noty);
40
+ }
41
+ /**
42
+ * Higher order function that takes a method whose responsibility is to create a
43
+ * **single** data fixture object and returns a new generator function that
44
+ * allows you to create 1 or many of those fixtures. Fixture generator function
45
+ * that's returned supports passing optional `num` and `overrides` params.
46
+ *
47
+ * @example
48
+ *
49
+ * const generateInvoice = (overrides) => ({ id: uuid(), balance: 15799, classification: "Adult Use", ...overrides});
50
+ * const generateInvoices = createFixtureGenerator(generateInvoice);
51
+ *
52
+ * generateInvoices() // => Single invoice object
53
+ * generateInvoices(1) // => Single invoice object
54
+ * generateInvoices(1, { foo: 'bar' }) // => Single invoice object, override `foo` to equal `'bar'`
55
+ * generateInvoices({ foo: 'bar' }) // => Single invoice object, override `foo` to equal `'bar'`
56
+ * generateInvoices(10) // => Array of 10 invoice objects
57
+ * generateInvoices(10, { foo: 'bar' }) // => Array of 10 invoice objects, override `foo` to equal `'bar'` in each
58
+ *
59
+ * @param {function} fixtureFn - Method that generates a JSON data fixture.
60
+ * @returns {function}
61
+ * @returns {array|object} - Array of fixture objects or single object if n = 1.
62
+ */
63
+ export function createFixtureGenerator(fixtureFn) {
64
+ return (num = 1, overrides = {}) => {
65
+ // if passed a number of 1 or an object, we're only going to generate a
66
+ // single data object and treat `num` as the overrides.
67
+ if (typeof num !== 'number' || num === 1) {
68
+ return fixtureFn(num);
69
+ }
70
+ // Otherwise, let's generate however many requested data objects
71
+ return Array.apply(null, Array(num)).map(() => fixtureFn(overrides));
72
+ };
73
+ }
74
+ export * from './api';
75
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"src/","sources":["index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,yBAAyB,EAAE,MAAM,sBAAsB,CAAC;AACzE,OAAO,EAAE,OAAO,IAAI,SAAS,EAAE,MAAM,6BAA6B,CAAC;AAEnE;;;;;;GAMG;AACH,MAAM,UAAU,sBAAsB,CACpC,SAAS,GAAG,8BAA8B;IAE1C,OAAO,yBAAyB,CAC9B,GAAG,EAAE,CAAC,CAAC,GAAG,MAAM,CAAC,gBAAgB,CAAC,SAAS,CAAC,CAAC,EAC7C,E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0 +1 @@
1
+ export {};
@@ -0,0 +1,32 @@
1
+ import { createFixtureGenerator } from "./index";
2
+ describe('createFixtureGenerator()', () => {
3
+ it('returns a function that can generate an array of data objects', () => {
4
+ const generator = (overrides) => ({
5
+ foo: 'bar',
6
+ bar: 'baz',
7
+ ...overrides,
8
+ });
9
+ expect(createFixtureGenerator(generator)(5)).toEqual([
10
+ { foo: 'bar', bar: 'baz' },
11
+ { foo: 'bar', bar: 'baz' },
12
+ { foo: 'bar', bar: 'baz' },
13
+ { foo: 'bar', bar: 'baz' },
14
+ { foo: 'bar', bar: 'baz' },
15
+ ]);
16
+ expect(createFixtureGenerator(generator)(3, { bar: 'yak' })).toEqual([
17
+ { foo: 'bar', bar: 'yak' },
18
+ { foo: 'bar', bar: 'yak' },
19
+ { foo: 'bar', bar: 'yak' },
20
+ ]);
21
+ });
22
+ it('returns a function that can generate a single data object', () => {
23
+ const generator = (overrides) => ({
24
+ foo: 'bar',
25
+ bar: 'baz',
26
+ ...overrides,
27
+ });
28
+ expect(createFixtureGenerator(generator)()).toEqual({ foo: 'bar', bar: 'baz' });
29
+ expect(createFixtureGenerator(generator)({ bar: 'yak' })).toEqual({ foo: 'bar', bar: 'yak' });
30
+ });
31
+ });
32
+ //# sourceMappingURL=index.spec.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.spec.js","sourceRoot":"src/","sources":["index.spec.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,sBAAsB,EAAE,MAAM,SAAS,CAAC;AAEjD,QAAQ,CAAC,0BAA0B,EAAE,GAAG,EAAE;IACxC,EAAE,CAAC,+DAA+D,EAAE,GAAG,EAAE;QACvE,MAAM,SAAS,GAAG,CAAC,SAAS,EAAE,EAAE,CAAC,CAAC;YAChC,GAAG,EAAE,KAAK;YACV,GAAG,EAAE,KAAK;YACV,GAAG,SAAS;SACb,CAAC,CAAC;QAEH,MAAM,CAAC,sBAAsB,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC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C,CAAA"}
@@ -0,0 +1 @@
1
+ import '@testing-library/jest-dom';
@@ -0,0 +1,43 @@
1
+ import { vi } from 'vitest';
2
+ import { config } from '@vue/test-utils';
3
+ import '@testing-library/jest-dom';
4
+ config.global.mocks['$t'] = (msg) => msg;
5
+ const oldWindowLocation = global.window.location;
6
+ beforeAll(() => {
7
+ // @ts-expect-error
8
+ delete global.window.location;
9
+ // @ts-expect-error
10
+ global.window.location = Object.defineProperties({}, {
11
+ ...Object.getOwnPropertyDescriptors(oldWindowLocation),
12
+ assign: {
13
+ configurable: true,
14
+ value: vi.fn(),
15
+ },
16
+ href: {
17
+ configurable: true,
18
+ writable: true,
19
+ value: {
20
+ replace: vi.fn(),
21
+ },
22
+ },
23
+ });
24
+ window.open = vi.fn();
25
+ vi.mock('lodash-es/debounce', () => {
26
+ return { default: vi.fn((fn) => fn) };
27
+ });
28
+ });
29
+ afterAll(() => {
30
+ global.window.location = oldWindowLocation;
31
+ });
32
+ const IntersectionObserverMock = vi.fn(() => ({
33
+ get root() {
34
+ return;
35
+ },
36
+ disconnect: vi.fn(),
37
+ observe: vi.fn(),
38
+ takeRecords: vi.fn(),
39
+ unobserve: vi.fn(),
40
+ }));
41
+ vi.stubGlobal('IntersectionObserver', IntersectionObserverMock);
42
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ json: vi.fn().mockResolvedValue({}) }));
43
+ //# sourceMappingURL=setup-env.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"setup-env.js","sourceRoot":"src/","sources":["setup-env.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,EAAE,EAAE,MAAM,QAAQ,CAAC;AAC5B,OAAO,EAAE,MAAM,EAAE,MAAM,iBAAiB,CAAC;AACzC,OAAO,2BAA2B,CAAC;AAEnC,MAAM,CAAC,MAAM,CAAC,KAAK,CAAC,IAAI,CAAC,GAAG,CAAC,GAAG,EAAE,EAAE,CAAC,GAAG,CAAC;AAEzC,MAAM,iBAAiB,GAAG,MAAM,C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CAAC,sBAAsB,EAAE,wBAAwB,CAAC,CAAC;AAEhE,EAAE,CAAC,UAAU,CACX,OAAO,EACP,EAAE,CAAC,EAAE,EAAE,CAAC,iBAAiB,CAAC,EAAE,IAAI,EAAE,EAAE,CAAC,EAAE,EAAE,CAAC,iBAAiB,CAAC,EAAE,CAAC,EAAE,CAAC,CACnE,CAAC"}
File without changes
@@ -0,0 +1,22 @@
1
+ "use strict";
2
+ it('should stub window open method', () => {
3
+ const url = 'my-url';
4
+ const openSpy = vi.spyOn(window, 'open');
5
+ expect(openSpy).not.toHaveBeenCalled();
6
+ window.open(url);
7
+ expect(openSpy).toHaveBeenCalledWith(url);
8
+ });
9
+ it('should stub fetch method', async () => {
10
+ const url = 'my-url';
11
+ const fetchSpy = vi.spyOn(globalThis, 'fetch');
12
+ expect(fetchSpy).not.toHaveBeenCalled();
13
+ await fetch(url);
14
+ expect(fetchSpy).toHaveBeenCalledWith(url);
15
+ });
16
+ it.each([['disconnect'], ['observe'], ['takeRecords'], ['unobserve']])('should stub intersection observer %s method', (method) => {
17
+ const observer = new globalThis.IntersectionObserver(() => ({}), {});
18
+ const methodSpy = vi.spyOn(observer, method);
19
+ observer[method]();
20
+ expect(methodSpy).toHaveBeenCalled();
21
+ });
22
+ //# sourceMappingURL=setup-env.spec.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"setup-env.spec.js","sourceRoot":"src/","sources":["setup-env.spec.ts"],"names":[],"mappings":";AAAA,EAAE,CAAC,gCAAgC,EAAE,GAAG,EAAE;IACxC,MAAM,GAAG,GAAG,QAAQ,CAAC;IAErB,MAAM,OAAO,GAAG,EAAE,CAAC,KAAK,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAEzC,MAAM,CAAC,OAAO,CAAC,CAAC,GAAG,CAAC,gBAAgB,EAAE,CAAC;IAEvC,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;IAEjB,MAAM,CAAC,OAAO,CAAC,CAAC,oBAAoB,CAAC,GAAG,CAAC,CAAC;AAC5C,CAAC,CAAC,CAAC;AAEH,EAAE,CAAC,0BAA0B,EAAE,KAAK,IAAI,EAAE;IACxC,MAAM,GAAG,GAAG,QAAQ,CAAC;IAErB,MAAM,QAAQ,GAAG,EAAE,CAAC,KAAK,CAAC,UAAU,EAAE,OAAO,CAAC,CAAC;IAE/C,MAAM,CAAC,QAAQ,CAAC,CAAC,GAAG,CAAC,gBAAgB,EAAE,CAAC;IAExC,MAAM,KAAK,CAAC,GAAG,CAAC,CAAC;IAEjB,MAAM,CAAC,QAAQ,CAAC,CAAC,oBAAoB,CAAC,GAAG,CAAC,CAAC;AAC7C,CAAC,CAAC,CAAC;AAEH,EAAE,CAAC,IAAI,CAAC,CAAC,CAAC,YAAY,CAAC,EAAE,CAAC,SAAS,CAAC,EAAE,CAAC,aAAa,CAAC,EAAE,CAAC,WAAW,CAAC,CAAC,CAAC,CACpE,6CAA6C,EAC7C,CAAC,MAAW,EAAE,EAAE;IACd,MAAM,QAAQ,GAAG,IAAI,UAAU,CAAC,oBAAoB,CAAC,GAAG,EAAE,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC;IAErE,MAAM,SAAS,GAAG,EAAE,CAAC,KAAK,CAAC,QAAQ,EAAE,MAAM,CAAC,CAAC;IAE7C,QAAQ,CAAC,MAAM,CAAC,EAAE,CAAC;IAEnB,MAAM,CAAC,SAAS,CAAC,CAAC,gBAAgB,EAAE,CAAC;AACvC,CAAC,CACF,CAAC"}
package/package.json ADDED
@@ -0,0 +1,57 @@
1
+ {
2
+ "name": "@leaflink/dom-testing-utils",
3
+ "version": "0.0.0-PR-14--3ff9079",
4
+ "description": "Frontend DOM testing utilities",
5
+ "engines": {
6
+ "node": ">=16",
7
+ "npm": ">=8"
8
+ },
9
+ "exports": {
10
+ ".": "./dist/index.js"
11
+ },
12
+ "type": "module",
13
+ "types": "./dist/index.d.ts",
14
+ "publishConfig": {
15
+ "access": "public"
16
+ },
17
+ "files": [
18
+ "dist"
19
+ ],
20
+ "scripts": {
21
+ "build": "tsc",
22
+ "lint:commits": "commitlint",
23
+ "test": "vitest --reporter verbose"
24
+ },
25
+ "license": "MIT",
26
+ "devDependencies": {
27
+ "@commitlint/cli": "^17.4.4",
28
+ "@commitlint/config-conventional": "^17.4.4",
29
+ "@vitest/coverage-c8": "^0.29.2",
30
+ "jsdom": "^21.1.1",
31
+ "typescript": "^4.9.5",
32
+ "vite": "^4.1.4",
33
+ "vitest": "^0.29.3"
34
+ },
35
+ "commitlint": {
36
+ "extends": [
37
+ "@commitlint/config-conventional"
38
+ ],
39
+ "rules": {
40
+ "scope-case": [
41
+ 0
42
+ ],
43
+ "body-max-line-length": [
44
+ 0
45
+ ]
46
+ }
47
+ },
48
+ "dependencies": {
49
+ "@testing-library/cypress": "^9.0.0",
50
+ "@testing-library/jest-dom": "^5.16.5",
51
+ "@testing-library/user-event": "^14.4.3",
52
+ "@testing-library/vue": "^7.0.0",
53
+ "@types/segment-analytics": "^0.0.34",
54
+ "eslint-plugin-testing-library": "^5.10.2",
55
+ "msw": "^0.27.2"
56
+ }
57
+ }