frontend_testing.md 31,8 КБ
Newer Older
1
2
3
# Frontend testing standards and style guidelines

There are two types of test suites you'll encounter while developing frontend code
GitLab Bot's avatar
GitLab Bot включено в состав коммита
4
at GitLab. We use Karma with Jasmine and Jest for JavaScript unit and integration testing,
5
6
7
8
9
10
11
12
13
14
15
and RSpec feature tests with Capybara for e2e (end-to-end) integration testing.

Unit and feature tests need to be written for all new features.
Most of the time, you should use [RSpec] for your feature tests.

Regression tests should be written for bug fixes to prevent them from recurring
in the future.

See the [Testing Standards and Style Guidelines](index.md) page for more
information on general testing practices at GitLab.

GitLab Bot's avatar
GitLab Bot включено в состав коммита
16
17
18
19
## Vue.js testing

If you are looking for a guide on Vue component testing, you can jump right away to this [section][vue-test].

Luke Bennett's avatar
Luke Bennett включено в состав коммита
20
21
## Jest

Winnie Hellmann's avatar
Winnie Hellmann включено в состав коммита
22
23
We have started to migrate frontend tests to the [Jest](https://jestjs.io) testing framework (see also the corresponding
[epic](https://gitlab.com/groups/gitlab-org/-/epics/895)).
Luke Bennett's avatar
Luke Bennett включено в состав коммита
24
25
26

Jest tests can be found in `/spec/frontend` and `/ee/spec/frontend` in EE.

GitLab Bot's avatar
GitLab Bot включено в состав коммита
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
> **Note:**
>
> Most examples have a Jest and Karma example. See the Karma examples only as explanation to what's going on in the code, should you stumble over some usescases during your discovery. The Jest examples are the one you should follow.

## Karma test suite

While GitLab is switching over to [Jest][jest] you'll still find Karma tests in our application. [Karma][karma] is a test runner which uses [Jasmine] as its test
framework. Jest also uses Jasmine as foundation, that's why it's looking quite similar.

Karma tests live in `spec/javascripts/` and `/ee/spec/javascripts` in EE.

`app/assets/javascripts/behaviors/autosize.js`
might have a corresponding `spec/javascripts/behaviors/autosize_spec.js` file.

Keep in mind that in a CI environment, these tests are run in a headless
browser and you will not have access to certain APIs, such as
[`Notification`](https://developer.mozilla.org/en-US/docs/Web/API/notification),
which have to be stubbed.

Paul Slaughter's avatar
Paul Slaughter включено в состав коммита
46
47
48
49
50
51
### When should I use Jest over Karma?

If you need to update an existing Karma test file (found in `spec/javascripts`), you do not
need to migrate the whole spec to Jest. Simply updating the Karma spec to test your change
is fine. It is probably more appropriate to migrate to Jest in a separate merge request.

GitLab Bot's avatar
GitLab Bot включено в состав коммита
52
If you create a new test file, it needs to be created in Jest. This will
Paul Slaughter's avatar
Paul Slaughter включено в состав коммита
53
54
55
56
57
help support our migration and we think you'll love using Jest.

As always, please use discretion. Jest solves a lot of issues we experienced in Karma and
provides a better developer experience, however there are potentially unexpected issues
which could arise (especially with testing against browser specific features).
Luke Bennett's avatar
Luke Bennett включено в состав коммита
58

Winnie Hellmann's avatar
Winnie Hellmann включено в состав коммита
59
60
### Differences to Karma

GitLab Bot's avatar
GitLab Bot включено в состав коммита
61
- Jest runs in a Node.js environment, not in a browser. Support for running Jest tests in a browser [is planned](https://gitlab.com/gitlab-org/gitlab/-/issues/26982).
Winnie Hellmann's avatar
Winnie Hellmann включено в состав коммита
62
- Because Jest runs in a Node.js environment, it uses [jsdom](https://github.com/jsdom/jsdom) by default. See also its [limitations](#limitations-of-jsdom) below.
Winnie Hellmann's avatar
Winnie Hellmann включено в состав коммита
63
- Jest does not have access to Webpack loaders or aliases.
GitLab Bot's avatar
GitLab Bot включено в состав коммита
64
  The aliases used by Jest are defined in its [own config](https://gitlab.com/gitlab-org/gitlab/blob/master/jest.config.js).
Winnie Hellmann's avatar
Winnie Hellmann включено в состав коммита
65
66
- All calls to `setTimeout` and `setInterval` are mocked away. See also [Jest Timer Mocks](https://jestjs.io/docs/en/timer-mocks).
- `rewire` is not required because Jest supports mocking modules. See also [Manual Mocks](https://jestjs.io/docs/en/manual-mocks).
Winnie Hellmann's avatar
Winnie Hellmann включено в состав коммита
67
68
69
- No [context object](https://jasmine.github.io/tutorials/your_first_suite#section-The_%3Ccode%3Ethis%3C/code%3E_keyword) is passed to tests in Jest.
  This means sharing `this.something` between `beforeEach()` and `it()` for example does not work.
  Instead you should declare shared variables in the context that they are needed (via `const` / `let`).
Winnie Hellmann's avatar
Winnie Hellmann включено в состав коммита
70
71
72
73
74
- The following will cause tests to fail in Jest:
  - Unmocked requests.
  - Unhandled Promise rejections.
  - Calls to `console.warn`, including warnings from libraries like Vue.

Winnie Hellmann's avatar
Winnie Hellmann включено в состав коммита
75
76
77
78
79
80
81
82
83
### Limitations of jsdom

As mentioned [above](#differences-to-karma), Jest uses jsdom instead of a browser for running tests.
This comes with a number of limitations, namely:

- [No scrolling support](https://github.com/jsdom/jsdom/blob/15.1.1/lib/jsdom/browser/Window.js#L623-L625)
- [No element sizes or positions](https://github.com/jsdom/jsdom/blob/15.1.1/lib/jsdom/living/nodes/Element-impl.js#L334-L371)
- [No layout engine](https://github.com/jsdom/jsdom/issues/1322) in general

GitLab Bot's avatar
GitLab Bot включено в состав коммита
84
See also the issue for [support running Jest tests in browsers](https://gitlab.com/gitlab-org/gitlab/-/issues/26982).
Winnie Hellmann's avatar
Winnie Hellmann включено в состав коммита
85

Simon Knox's avatar
Simon Knox включено в состав коммита
86
87
88
89
### Debugging Jest tests

Running `yarn jest-debug` will run Jest in debug mode, allowing you to debug/inspect as described in the [Jest docs](https://jestjs.io/docs/en/troubleshooting#tests-are-failing-and-you-don-t-know-why).

Luke Bennett's avatar
Luke Bennett включено в состав коммита
90
91
92
### Timeout error

The default timeout for Jest is set in
GitLab Bot's avatar
GitLab Bot включено в состав коммита
93
[`/spec/frontend/test_setup.js`](https://gitlab.com/gitlab-org/gitlab/blob/master/spec/frontend/test_setup.js).
Luke Bennett's avatar
Luke Bennett включено в состав коммита
94
95
96
97
98

If your test exceeds that time, it will fail.

If you cannot improve the performance of the tests, you can increase the timeout
for a specific test using
GitLab Bot's avatar
GitLab Bot включено в состав коммита
99
[`setTestTimeout`](https://gitlab.com/gitlab-org/gitlab/blob/master/spec/frontend/helpers/timeout.js).
Luke Bennett's avatar
Luke Bennett включено в состав коммита
100
101

```javascript
Luke Bennett's avatar
Luke Bennett включено в состав коммита
102
import { setTestTimeout } from 'helpers/timeout';
Luke Bennett's avatar
Luke Bennett включено в состав коммита
103
104

describe('Component', () => {
Luke Bennett's avatar
Luke Bennett включено в состав коммита
105
106
107
108
  it('does something amazing', () => {
    setTestTimeout(500);
    // ...
  });
Luke Bennett's avatar
Luke Bennett включено в состав коммита
109
110
111
112
113
});
```

Remember that the performance of each test depends on the environment.

GitLab Bot's avatar
GitLab Bot включено в состав коммита
114
## What and how to test
Mike Greiling's avatar
Mike Greiling включено в состав коммита
115

GitLab Bot's avatar
GitLab Bot включено в состав коммита
116
Before jumping into more gritty details about Jest-specific workflows like mocks and spies, we should briefly cover what to test with Jest.
Martin Hanzel's avatar
Martin Hanzel включено в состав коммита
117

GitLab Bot's avatar
GitLab Bot включено в состав коммита
118
### Don't test the library
Martin Hanzel's avatar
Martin Hanzel включено в состав коммита
119

GitLab Bot's avatar
GitLab Bot включено в состав коммита
120
121
Libraries are an integral part of any JavaScript developer's life. The general advice would be to not test library internals, but expect that the library knows what it's supposed to do and has test coverage on its own.
A general example could be something like this
Martin Hanzel's avatar
Martin Hanzel включено в состав коммита
122

GitLab Bot's avatar
GitLab Bot включено в состав коммита
123
124
```javascript
import { convertToFahrenheit } from 'temperatureLibrary'
Martin Hanzel's avatar
Martin Hanzel включено в состав коммита
125

GitLab Bot's avatar
GitLab Bot включено в состав коммита
126
127
128
129
function getFahrenheit(celsius) {
  return convertToFahrenheit(celsius)
}
```
Martin Hanzel's avatar
Martin Hanzel включено в состав коммита
130

GitLab Bot's avatar
GitLab Bot включено в состав коммита
131
It does not make sense to test our `getFahrenheit` function because underneath it does nothing else but invoking the library function, and we can expect that one is working as intended. (Simplified, I know)
Martin Hanzel's avatar
Martin Hanzel включено в состав коммита
132

GitLab Bot's avatar
GitLab Bot включено в состав коммита
133
Let's take a short look into Vue land. Vue is a critical part of the GitLab JavaScript codebase. When writing specs for Vue components, a common gotcha is to actually end up testing Vue provided functionality, because it appears to be the easiest thing to test. Here's an example taken from our codebase.
Mike Greiling's avatar
Mike Greiling включено в состав коммита
134

GitLab Bot's avatar
GitLab Bot включено в состав коммита
135
136
137
138
139
140
141
142
143
```javascript
// Component
{
  computed: {
    hasMetricTypes() {
      return this.metricTypes.length;
    },
}
```
Martin Hanzel's avatar
Martin Hanzel включено в состав коммита
144

GitLab Bot's avatar
GitLab Bot включено в состав коммита
145
and here's the corresponding spec
Mike Greiling's avatar
Mike Greiling включено в состав коммита
146

GitLab Bot's avatar
GitLab Bot включено в состав коммита
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
```javascript
 describe('computed', () => {
    describe('hasMetricTypes', () => {
      it('returns true if metricTypes exist', () => {
        factory({ metricTypes });
        expect(wrapper.vm.hasMetricTypes).toBe(2);
      });

      it('returns true if no metricTypes exist', () => {
        factory();
        expect(wrapper.vm.hasMetricTypes).toBe(0);
      });
    });
});
```
Martin Hanzel's avatar
Martin Hanzel включено в состав коммита
162

GitLab Bot's avatar
GitLab Bot включено в состав коммита
163
Testing the `hasMetricTypes` computed prop would seem like a given, but to test if the computed property is returning the length of `metricTypes`, is testing the Vue library itself. There is no value in this, besides it adding to the test suite. Better is to test it in the way the user interacts with it. Probably through the template.
Martin Hanzel's avatar
Martin Hanzel включено в состав коммита
164

GitLab Bot's avatar
GitLab Bot включено в состав коммита
165
Keep an eye out for these kinds of tests, as they just make updating logic more fragile and tedious than it needs to be. This is also true for other libraries.
GitLab Bot's avatar
GitLab Bot включено в состав коммита
166

GitLab Bot's avatar
GitLab Bot включено в состав коммита
167
Some more examples can be found in the [Frontend unit tests section](testing_levels.md#frontend-unit-tests)
GitLab Bot's avatar
GitLab Bot включено в состав коммита
168

GitLab Bot's avatar
GitLab Bot включено в состав коммита
169
### Don't test your mock
GitLab Bot's avatar
GitLab Bot включено в состав коммита
170

GitLab Bot's avatar
GitLab Bot включено в состав коммита
171
Another common gotcha is that the specs end up verifying the mock is working. If you are using mocks, the mock should support the test, but not be the target of the test.
GitLab Bot's avatar
GitLab Bot включено в состав коммита
172

GitLab Bot's avatar
GitLab Bot включено в состав коммита
173
**Bad:**
GitLab Bot's avatar
GitLab Bot включено в состав коммита
174
175

```javascript
GitLab Bot's avatar
GitLab Bot включено в состав коммита
176
177
const spy = jest.spyOn(idGenerator, 'create')
spy.mockImplementation = () = '1234'
GitLab Bot's avatar
GitLab Bot включено в состав коммита
178

GitLab Bot's avatar
GitLab Bot включено в состав коммита
179
180
expect(idGenerator.create()).toBe('1234')
```
GitLab Bot's avatar
GitLab Bot включено в состав коммита
181

GitLab Bot's avatar
GitLab Bot включено в состав коммита
182
**Good:**
GitLab Bot's avatar
GitLab Bot включено в состав коммита
183

GitLab Bot's avatar
GitLab Bot включено в состав коммита
184
185
186
187
188
189
```javascript
const spy = jest.spyOn(idGenerator, 'create')
spy.mockImplementation = () = '1234'

// Actually focusing on the logic of your component and just leverage the controllable mocks output
expect(wrapper.find('div').html()).toBe('<div id="1234">...</div>')
GitLab Bot's avatar
GitLab Bot включено в состав коммита
190
191
```

GitLab Bot's avatar
GitLab Bot включено в состав коммита
192
### Follow the user
193

GitLab Bot's avatar
GitLab Bot включено в состав коммита
194
The line between unit and integration tests can be quite blurry in a component heavy world. The most important guideline to give is the following:
195

GitLab Bot's avatar
GitLab Bot включено в состав коммита
196
197
- Write clean unit tests if there is actual value in testing a complex piece of logic in isolation to prevent it from breaking in the future
- Otherwise, try to write your specs as close to the user's flow as possible
198

GitLab Bot's avatar
GitLab Bot включено в состав коммита
199
For example, it's better to use the generated markup to trigger a button click and validate the markup changed accordingly than to call a method manually and verify data structures or computed properties. There's always the chance of accidentally breaking the user flow, while the tests pass and provide a false sense of security.
200

GitLab Bot's avatar
GitLab Bot включено в состав коммита
201
## Common practices
202

GitLab Bot's avatar
GitLab Bot включено в состав коммита
203
204
Following you'll find some general common practices you will find as part of our testsuite. Should you stumble over something not following this guide, ideally fix it right away. 🎉

GitLab Bot's avatar
GitLab Bot включено в состав коммита
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
### How to query DOM elements

When it comes to querying DOM elements in your tests, it is best to uniquely target the element, without adding additional attributes specifically for testing purposes. Sometimes this cannot be done feasibly. In these cases, adding test attributes to simplify the selectors might be the best option.

Preferentially, in component testing with `@vue/test-utils`, you should query for child components using the component itself. Otherwise, try to use an existing attribute like `name` or a Vue `ref` (if using `@vue/test-utils`):

```javascript
it('exists', () => {
    wrapper.find(FooComponent);
    wrapper.find('input[name=foo]');
    wrapper.find({ ref: 'foo'});
    wrapper.find('.js-foo');
});
```

It is not recommended that you add `.js-*` classes just for testing purposes. Only do this if there are no other feasible options available.

Do not use a `.qa-*` class or `data-qa-selector` attribute for any tests other than QA end-to-end testing.

GitLab Bot's avatar
GitLab Bot включено в состав коммита
224
### Naming unit tests
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250

When writing describe test blocks to test specific functions/methods,
please use the method name as the describe block name.

```javascript
// Good
describe('methodName', () => {
  it('passes', () => {
    expect(true).toEqual(true);
  });
});

// Bad
describe('#methodName', () => {
  it('passes', () => {
    expect(true).toEqual(true);
  });
});

// Bad
describe('.methodName', () => {
  it('passes', () => {
    expect(true).toEqual(true);
  });
});
```
Mike Greiling's avatar
Mike Greiling включено в состав коммита
251

GitLab Bot's avatar
GitLab Bot включено в состав коммита
252
### Testing promises
253

GitLab Bot's avatar
GitLab Bot включено в состав коммита
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
When testing Promises you should always make sure that the test is asynchronous and rejections are handled. It's now possible to use the `async/await` syntax in the test suite:

```javascript
it('tests a promise', async () => {
  const users = await fetchUsers()
  expect(users.length).toBe(42)
});

it('tests a promise rejection', async () => {
  expect.assertions(1);
  try {
    await user.getUserName(1);
  } catch (e) {
    expect(e).toEqual({
      error: 'User with 1 not found.',
    });
  }
});
```

You can also work with Promise chains. In this case, you can make use of the `done` callback and `done.fail` in case an error occurred. Following are some examples:
275
276
277

```javascript
// Good
Mike Greiling's avatar
Mike Greiling включено в состав коммита
278
it('tests a promise', done => {
279
  promise
Mike Greiling's avatar
Mike Greiling включено в состав коммита
280
    .then(data => {
281
282
283
284
285
286
287
      expect(data).toBe(asExpected);
    })
    .then(done)
    .catch(done.fail);
});

// Good
Mike Greiling's avatar
Mike Greiling включено в состав коммита
288
it('tests a promise rejection', done => {
289
290
  promise
    .then(done.fail)
Mike Greiling's avatar
Mike Greiling включено в состав коммита
291
    .catch(error => {
292
293
294
295
296
297
298
299
      expect(error).toBe(expectedError);
    })
    .then(done)
    .catch(done.fail);
});

// Bad (missing done callback)
it('tests a promise', () => {
Mike Greiling's avatar
Mike Greiling включено в состав коммита
300
301
302
  promise.then(data => {
    expect(data).toBe(asExpected);
  });
303
304
305
});

// Bad (missing catch)
Mike Greiling's avatar
Mike Greiling включено в состав коммита
306
it('tests a promise', done => {
307
  promise
Mike Greiling's avatar
Mike Greiling включено в состав коммита
308
    .then(data => {
309
310
      expect(data).toBe(asExpected);
    })
Mike Greiling's avatar
Mike Greiling включено в состав коммита
311
    .then(done);
312
313
314
});

// Bad (use done.fail in asynchronous tests)
Mike Greiling's avatar
Mike Greiling включено в состав коммита
315
it('tests a promise', done => {
316
  promise
Mike Greiling's avatar
Mike Greiling включено в состав коммита
317
    .then(data => {
318
319
320
      expect(data).toBe(asExpected);
    })
    .then(done)
Mike Greiling's avatar
Mike Greiling включено в состав коммита
321
    .catch(fail);
322
323
324
});

// Bad (missing catch)
Mike Greiling's avatar
Mike Greiling включено в состав коммита
325
it('tests a promise rejection', done => {
326
  promise
Mike Greiling's avatar
Mike Greiling включено в состав коммита
327
    .catch(error => {
328
329
      expect(error).toBe(expectedError);
    })
Mike Greiling's avatar
Mike Greiling включено в состав коммита
330
    .then(done);
331
332
333
});
```

GitLab Bot's avatar
GitLab Bot включено в состав коммита
334
### Manipulating Time
335

GitLab Bot's avatar
GitLab Bot включено в состав коммита
336
Sometimes we have to test time-sensitive code. For example, recurring events that run every X amount of seconds or similar. Here you'll find some strategies to deal with that:
337

GitLab Bot's avatar
GitLab Bot включено в состав коммита
338
#### `setTimeout()` / `setInterval()` in application
Mike Greiling's avatar
Mike Greiling включено в состав коммита
339

GitLab Bot's avatar
GitLab Bot включено в состав коммита
340
341
342
343
If the application itself is waiting for some time, mock await the waiting. In Jest this is already
[done by default](https://gitlab.com/gitlab-org/gitlab/blob/a2128edfee799e49a8732bfa235e2c5e14949c68/jest.config.js#L47)
(see also [Jest Timer Mocks](https://jestjs.io/docs/en/timer-mocks)). In Karma you can use the
[Jasmine mock clock](https://jasmine.github.io/api/2.9/Clock.html).
Mike Greiling's avatar
Mike Greiling включено в состав коммита
344

GitLab Bot's avatar
GitLab Bot включено в состав коммита
345
346
347
348
349
350
```javascript
const doSomethingLater = () => {
  setTimeout(() => {
    // do something
  }, 4000);
};
Luke Bennett's avatar
Luke Bennett включено в состав коммита
351
```
Winnie Hellmann's avatar
Winnie Hellmann включено в состав коммита
352

GitLab Bot's avatar
GitLab Bot включено в состав коммита
353
**in Jest:**
Mike Greiling's avatar
Mike Greiling включено в состав коммита
354

GitLab Bot's avatar
GitLab Bot включено в состав коммита
355
356
357
358
```javascript
it('does something', () => {
  doSomethingLater();
  jest.runAllTimers();
Mike Greiling's avatar
Mike Greiling включено в состав коммита
359

GitLab Bot's avatar
GitLab Bot включено в состав коммита
360
  expect(something).toBe('done');
Mike Greiling's avatar
Mike Greiling включено в состав коммита
361
362
363
});
```

GitLab Bot's avatar
GitLab Bot включено в состав коммита
364
**in Karma:**
Mike Greiling's avatar
Mike Greiling включено в состав коммита
365

GitLab Bot's avatar
GitLab Bot включено в состав коммита
366
367
368
```javascript
it('does something', () => {
  jasmine.clock().install();
369

GitLab Bot's avatar
GitLab Bot включено в состав коммита
370
371
372
373
374
375
376
377
378
  doSomethingLater();
  jasmine.clock().tick(4000);

  expect(something).toBe('done');
  jasmine.clock().uninstall();
});
```

### Waiting in tests
Winnie Hellmann's avatar
Winnie Hellmann включено в состав коммита
379

Winnie Hellmann's avatar
Winnie Hellmann включено в состав коммита
380
381
Sometimes a test needs to wait for something to happen in the application before it continues.
Avoid using [`setTimeout`](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout)
GitLab Bot's avatar
GitLab Bot включено в состав коммита
382
because it makes the reason for waiting unclear and if used within Karma with a time larger than zero it will slow down our test suite.
Winnie Hellmann's avatar
Winnie Hellmann включено в состав коммита
383
384
Instead use one of the following approaches.

GitLab Bot's avatar
GitLab Bot включено в состав коммита
385
#### Promises and Ajax calls
Winnie Hellmann's avatar
Winnie Hellmann включено в состав коммита
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404

Register handler functions to wait for the `Promise` to be resolved.

```javascript
const askTheServer = () => {
  return axios
    .get('/endpoint')
    .then(response => {
      // do something
    })
    .catch(error => {
      // do something else
    });
};
```

**in Jest:**

```javascript
GitLab Bot's avatar
GitLab Bot включено в состав коммита
405
406
407
it('waits for an Ajax call', async () => {
  await askTheServer()
  expect(something).toBe('done');
Winnie Hellmann's avatar
Winnie Hellmann включено в состав коммита
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
});
```

**in Karma:**

```javascript
it('waits for an Ajax call', done => {
  askTheServer()
    .then(() => {
      expect(something).toBe('done');
    })
    .then(done)
    .catch(done.fail);
});
```

GitLab Bot's avatar
GitLab Bot включено в состав коммита
424
If you are not able to register handlers to the `Promise`, for example because it is executed in a synchronous Vue life cycle hook, please take a look at the [waitFor](#wait-until-axios-requests-finish) helpers or you can flush all pending `Promise`s:
Winnie Hellmann's avatar
Winnie Hellmann включено в состав коммита
425
426
427
428
429
430
431
432
433
434
435
436

**in Jest:**

```javascript
it('waits for an Ajax call', () => {
  synchronousFunction();
  jest.runAllTicks();

  expect(something).toBe('done');
});
```

GitLab Bot's avatar
GitLab Bot включено в состав коммита
437
#### Vue rendering
Winnie Hellmann's avatar
Winnie Hellmann включено в состав коммита
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469

To wait until a Vue component is re-rendered, use either of the equivalent
[`Vue.nextTick()`](https://vuejs.org/v2/api/#Vue-nextTick) or `vm.$nextTick()`.

**in Jest:**

```javascript
it('renders something', () => {
  wrapper.setProps({ value: 'new value' });

  return wrapper.vm.$nextTick().then(() => {
    expect(wrapper.text()).toBe('new value');
  });
});
```

**in Karma:**

```javascript
it('renders something', done => {
  wrapper.setProps({ value: 'new value' });

  wrapper.vm
    .$nextTick()
    .then(() => {
      expect(wrapper.text()).toBe('new value');
    })
    .then(done)
    .catch(done.fail);
});
```

GitLab Bot's avatar
GitLab Bot включено в состав коммита
470
#### Events
Winnie Hellmann's avatar
Winnie Hellmann включено в состав коммита
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500

If the application triggers an event that you need to wait for in your test, register an event handler which contains
the assertions:

```javascript
it('waits for an event', done => {
  eventHub.$once('someEvent', eventHandler);

  someFunction();

  function eventHandler() {
    expect(something).toBe('done');
    done();
  }
});
```

In Jest you can also use a `Promise` for this:

```javascript
it('waits for an event', () => {
  const eventTriggered = new Promise(resolve => eventHub.$once('someEvent', resolve));

  someFunction();

  return eventTriggered.then(() => {
    expect(something).toBe('done');
  });
});
```
Winnie Hellmann's avatar
Winnie Hellmann включено в состав коммита
501

GitLab Bot's avatar
GitLab Bot включено в состав коммита
502
### Ensuring that tests are isolated
GitLab Bot's avatar
GitLab Bot включено в состав коммита
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532

Tests are normally architected in a pattern which requires a recurring setup and breakdown of the component under test. This is done by making use of the `beforeEach` and `afterEach` hooks.

Example

```javascript
  let wrapper;

  beforeEach(() => {
    wrapper = mount(Component);
  });

  afterEach(() => {
    wrapper.destroy();
  });
```

When looking at this initially you'd suspect that the component is setup before each test and then broken down afterwards, providing isolation between tests.

This is however not entirely true as the `destroy` method does not remove everything which has been mutated on the `wrapper` object. For functional components, destroy only removes the rendered DOM elements from the document.

In order to ensure that a clean wrapper object and DOM are being used in each test, the breakdown of the component should rather be performed as follows:

```javascript
  afterEach(() => {
    wrapper.destroy();
    wrapper = null;
  });
```

GitLab Bot's avatar
GitLab Bot включено в состав коммита
533
See also the [Vue Test Utils documentation on `destroy`](https://vue-test-utils.vuejs.org/api/wrapper/#destroy).
GitLab Bot's avatar
GitLab Bot включено в состав коммита
534

GitLab Bot's avatar
GitLab Bot включено в состав коммита
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
## Factories

TBU

## Mocking Strategies with Jest

### Stubbing and Mocking

Jasmine provides stubbing and mocking capabilities. There are some subtle differences in how to use it within Karma and Jest.

Stubs or spies are often used synonymously. In Jest it's quite easy thanks to the `.spyOn` method. [Official docs][jestspy]
The more challenging part are mocks, which can be used for functions or even dependencies.

### Manual module mocks

Jest supports [manual module mocks](https://jestjs.io/docs/en/manual-mocks) by placing a mock in a `__mocks__/` directory next to the source module. **Don't do this.** We want to keep all of our test-related code in one place (the `spec/` folder), and the logic that Jest uses to apply mocks from `__mocks__/` is rather inconsistent.
Luke Bennett's avatar
Luke Bennett включено в состав коммита
551

GitLab Bot's avatar
GitLab Bot включено в состав коммита
552
553
554
555
556
557
Instead, our test runner detects manual mocks from `spec/frontend/mocks/`. Any mock placed here is automatically picked up and injected whenever you import its source module.

- Files in `spec/frontend/mocks/ce` will mock the corresponding CE module from `app/assets/javascripts`, mirroring the source module's path.
  - Example: `spec/frontend/mocks/ce/lib/utils/axios_utils` will mock the module `~/lib/utils/axios_utils`.
- Files in `spec/frontend/mocks/node` will mock NPM packages of the same name or path.
- We don't support mocking EE modules yet.
Luke Bennett's avatar
Luke Bennett включено в состав коммита
558

GitLab Bot's avatar
GitLab Bot включено в состав коммита
559
If a mock is found for which a source module doesn't exist, the test suite will fail. 'Virtual' mocks, or mocks that don't have a 1-to-1 association with a source module, are not supported yet.
Luke Bennett's avatar
Luke Bennett включено в состав коммита
560

GitLab Bot's avatar
GitLab Bot включено в состав коммита
561
### Writing a mock
562

GitLab Bot's avatar
GitLab Bot включено в состав коммита
563
Create a JS module in the appropriate place in `spec/frontend/mocks/`. That's it. It will automatically mock its source package in all tests.
564

GitLab Bot's avatar
GitLab Bot включено в состав коммита
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
Make sure that your mock's export has the same format as the mocked module. So, if you're mocking a CommonJS module, you'll need to use `module.exports` instead of the ES6 `export`.

It might be useful for a mock to expose a property that indicates if the mock was loaded. This way, tests can assert the presence of a mock without calling any logic and causing side-effects. The `~/lib/utils/axios_utils` module mock has such a property, `isMock`, that is `true` in the mock and undefined in the original class. Jest's mock functions also have a `mock` property that you can test.

### Bypassing mocks

If you ever need to import the original module in your tests, use [`jest.requireActual()`](https://jestjs.io/docs/en/jest-object#jestrequireactualmodulename) (or `jest.requireActual().default` for the default export). The `jest.mock()` and `jest.unmock()` won't have an effect on modules that have a manual mock, because mocks are imported and cached before any tests are run.

### Keep mocks light

Global mocks introduce magic and can affect how modules are imported in your tests. Try to keep them as light as possible and dependency-free. A global mock should be useful for any unit test. For example, the `axios_utils` and `jquery` module mocks throw an error when an HTTP request is attempted, since this is useful behaviour in &gt;99% of tests.

When in doubt, construct mocks in your test file using [`jest.mock()`](https://jestjs.io/docs/en/jest-object#jestmockmodulename-factory-options), [`jest.spyOn()`](https://jestjs.io/docs/en/jest-object#jestspyonobject-methodname), etc.

## Running Frontend Tests
580

Winnie Hellmann's avatar
Winnie Hellmann включено в состав коммита
581
For running the frontend tests, you need the following commands:
582

Mike Greiling's avatar
Mike Greiling включено в состав коммита
583
- `rake frontend:fixtures` (re-)generates [fixtures](#frontend-test-fixtures).
Winnie Hellmann's avatar
Winnie Hellmann включено в состав коммита
584
- `yarn test` executes the tests.
GitLab Bot's avatar
GitLab Bot включено в состав коммита
585
- `yarn jest` executes only the Jest tests.
586

Winnie Hellmann's avatar
Winnie Hellmann включено в состав коммита
587
As long as the fixtures don't change, `yarn test` is sufficient (and saves you some time).
588

GitLab Bot's avatar
GitLab Bot включено в состав коммита
589
590
591
592
### Live testing and focused testing -- Jest

While you work on a testsuite, you may want to run these specs in watch mode, so they rerun automatically on every save.

GitLab Bot's avatar
GitLab Bot включено в состав коммита
593
```shell
GitLab Bot's avatar
GitLab Bot включено в состав коммита
594
595
596
597
598
599
600
601
602
# Watch and rerun all specs matching the name icon
yarn jest --watch icon

# Watch and rerun one specifc file
yarn jest --watch path/to/spec/file.spec.js
```

You can also run some focused tests without the `--watch` flag

GitLab Bot's avatar
GitLab Bot включено в состав коммита
603
```shell
GitLab Bot's avatar
GitLab Bot включено в состав коммита
604
605
606
607
608
609
610
# Run specific jest file
yarn jest ./path/to/local_spec.js
# Run specific jest folder
yarn jest ./path/to/folder/
# Run all jest files which path contain term
yarn jest term
```
611

GitLab Bot's avatar
GitLab Bot включено в состав коммита
612
613
614
615
616
### Live testing and focused testing -- Karma

Karma allows something similar, but it's way more costly.

Running Karma with `yarn run karma-start` will compile the JavaScript
617
assets and run a server at `http://localhost:9876/` where it will automatically
Lukas Eipert's avatar
Lukas Eipert включено в состав коммита
618
run the tests on any browser which connects to it. You can enter that url on
619
620
multiple browsers at once to have it run the tests on each in parallel.

Luke Bennett's avatar
Luke Bennett включено в состав коммита
621
While Karma is running, any changes you make will instantly trigger a recompile
GitLab Bot's avatar
GitLab Bot включено в состав коммита
622
and retest of the **entire test suite**, so you can see instantly if you've broken
Luke Bennett's avatar
Luke Bennett включено в состав коммита
623
624
a test with your changes. You can use [Jasmine focused][jasmine-focus] or
excluded tests (with `fdescribe` or `xdescribe`) to get Karma to run only the
625
626
627
tests you want while you're working on a specific feature, but make sure to
remove these directives when you commit your code.

Luke Bennett's avatar
Luke Bennett включено в состав коммита
628
It is also possible to only run Karma on specific folders or files by filtering
Lukas Eipert's avatar
Lukas Eipert включено в состав коммита
629
the run tests via the argument `--filter-spec` or short `-f`:
Lukas Eipert's avatar
Lukas Eipert включено в состав коммита
630

GitLab Bot's avatar
GitLab Bot включено в состав коммита
631
```shell
Lukas Eipert's avatar
Lukas Eipert включено в состав коммита
632
633
634
# Run all files
yarn karma-start
# Run specific spec files
Lukas Eipert's avatar
Lukas Eipert включено в состав коммита
635
yarn karma-start --filter-spec profile/account/components/update_username_spec.js
Lukas Eipert's avatar
Lukas Eipert включено в состав коммита
636
# Run specific spec folder
Lukas Eipert's avatar
Lukas Eipert включено в состав коммита
637
638
639
yarn karma-start --filter-spec profile/account/components/
# Run all specs which path contain vue_shared or vie
yarn karma-start -f vue_shared -f vue_mr_widget
Lukas Eipert's avatar
Lukas Eipert включено в состав коммита
640
641
```

Mike Greiling's avatar
Mike Greiling включено в состав коммита
642
643
644
You can also use glob syntax to match files. Remember to put quotes around the
glob otherwise your shell may split it into multiple arguments:

GitLab Bot's avatar
GitLab Bot включено в состав коммита
645
```shell
Mike Greiling's avatar
Mike Greiling включено в состав коммита
646
647
648
649
# Run all specs named `file_spec` within the IDE subdirectory
yarn karma -f 'spec/javascripts/ide/**/file_spec.js'
```

Winnie Hellmann's avatar
Winnie Hellmann включено в состав коммита
650
651
652
653
654
## Frontend test fixtures

Code that is added to HAML templates (in `app/views/`) or makes Ajax requests to the backend has tests that require HTML or JSON from the backend.
Fixtures for these tests are located at:

Mike Greiling's avatar
Mike Greiling включено в состав коммита
655
656
- `spec/frontend/fixtures/`, for running tests in CE.
- `ee/spec/frontend/fixtures/`, for running tests in EE.
Winnie Hellmann's avatar
Winnie Hellmann включено в состав коммита
657
658
659
660
661
662
663
664
665
666

Fixture files in:

- The Karma test suite are served by [jasmine-jquery](https://github.com/velesin/jasmine-jquery).
- Jest use `spec/frontend/helpers/fixtures.js`.

The following are examples of tests that work for both Karma and Jest:

```javascript
it('makes a request', () => {
Mike Greiling's avatar
Mike Greiling включено в состав коммита
667
  const responseBody = getJSONFixture('some/fixture.json'); // loads spec/frontend/fixtures/some/fixture.json
Winnie Hellmann's avatar
Winnie Hellmann включено в состав коммита
668
  axiosMock.onGet(endpoint).reply(200, responseBody);
Marcel Amirault's avatar
Marcel Amirault включено в состав коммита
669

Winnie Hellmann's avatar
Winnie Hellmann включено в состав коммита
670
  myButton.click();
Marcel Amirault's avatar
Marcel Amirault включено в состав коммита
671

Winnie Hellmann's avatar
Winnie Hellmann включено в состав коммита
672
673
674
675
  // ...
});

it('uses some HTML element', () => {
Mike Greiling's avatar
Mike Greiling включено в состав коммита
676
  loadFixtures('some/page.html'); // loads spec/frontend/fixtures/some/page.html and adds it to the DOM
Marcel Amirault's avatar
Marcel Amirault включено в состав коммита
677

Winnie Hellmann's avatar
Winnie Hellmann включено в состав коммита
678
  const element = document.getElementById('#my-id');
Marcel Amirault's avatar
Marcel Amirault включено в состав коммита
679

Winnie Hellmann's avatar
Winnie Hellmann включено в состав коммита
680
681
682
683
  // ...
});
```

Mike Greiling's avatar
Mike Greiling включено в состав коммита
684
HTML and JSON fixtures are generated from backend views and controllers using RSpec (see `spec/frontend/fixtures/*.rb`).
Winnie Hellmann's avatar
Winnie Hellmann включено в состав коммита
685
686

For each fixture, the content of the `response` variable is stored in the output file.
GitLab Bot's avatar
GitLab Bot включено в состав коммита
687
This variable gets automatically set if the test is marked as `type: :request` or `type: :controller`.
Mike Greiling's avatar
Mike Greiling включено в состав коммита
688
Fixtures are regenerated using the `bin/rake frontend:fixtures` command but you can also generate them individually,
Mike Greiling's avatar
Mike Greiling включено в состав коммита
689
for example `bin/rspec spec/frontend/fixtures/merge_requests.rb`.
Winnie Hellmann's avatar
Winnie Hellmann включено в состав коммита
690
691
When creating a new fixture, it often makes sense to take a look at the corresponding tests for the endpoint in `(ee/)spec/controllers/` or `(ee/)spec/requests/`.

GitLab Bot's avatar
GitLab Bot включено в состав коммита
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
## Data-driven tests

Similar to [RSpec's parameterized tests](best_practices.md#table-based--parameterized-tests),
Jest supports data-driven tests for:

- Individual tests using [`test.each`](https://jestjs.io/docs/en/api#testeachtable-name-fn-timeout) (aliased to `it.each`).
- Groups of tests using [`describe.each`](https://jestjs.io/docs/en/api#describeeachtable-name-fn-timeout).

These can be useful for reducing repetition within tests. Each option can take an array of
data values or a tagged template literal.

For example:

```javascript
// function to test
const icon = status => status ? 'pipeline-passed' : 'pipeline-failed'
const message = status => status ? 'pipeline-passed' : 'pipeline-failed'

// test with array block
it.each([
    [false, 'pipeline-failed'],
    [true, 'pipeline-passed']
])('icon with %s will return %s',
 (status, icon) => {
    expect(renderPipeline(status)).toEqual(icon)
 }
);
```

```javascript
// test suite with tagged template literal block
describe.each`
    status   | icon                 | message
    ${false} | ${'pipeline-failed'} | ${'Pipeline failed - boo-urns'}
    ${true}  | ${'pipeline-passed'} | ${'Pipeline succeeded - win!'}
`('pipeline component', ({ status, icon, message }) => {
    it(`returns icon ${icon} with status ${status}`, () => {
        expect(icon(status)).toEqual(message)
    })

    it(`returns message ${message} with status ${status}`, () => {
        expect(message(status)).toEqual(message)
    })
});
```

738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
## Gotchas

### RSpec errors due to JavaScript

By default RSpec unit tests will not run JavaScript in the headless browser
and will simply rely on inspecting the HTML generated by rails.

If an integration test depends on JavaScript to run correctly, you need to make
sure the spec is configured to enable JavaScript when the tests are run. If you
don't do this you'll see vague error messages from the spec runner.

To enable a JavaScript driver in an `rspec` test, add `:js` to the
individual spec or the context block containing multiple specs that need
JavaScript enabled:

```ruby
# For one spec
it 'presents information about abuse report', :js do
  # assertions...
end

describe "Admin::AbuseReports", :js do
  it 'presents information about abuse report' do
    # assertions...
  end
  it 'shows buttons for adding to abuse report' do
    # assertions...
  end
end
```

Winnie Hellmann's avatar
Winnie Hellmann включено в состав коммита
769
770
## Overview of Frontend Testing Levels

GitLab Bot's avatar
GitLab Bot включено в состав коммита
771
772
Main information on frontend testing levels can be found in the [Testing Levels page](testing_levels.md).

Winnie Hellmann's avatar
Winnie Hellmann включено в состав коммита
773
774
Tests relevant for frontend development can be found at the following places:

GitLab Bot's avatar
GitLab Bot включено в состав коммита
775
776
777
778
779
- `spec/javascripts/`, for Karma tests
- `spec/frontend/`, for Jest tests
- `spec/features/`, for RSpec tests

RSpec runs complete [feature tests](testing_levels.md#frontend-feature-tests), while the Jest and Karma directories contain [frontend unit tests](testing_levels.md#frontend-unit-tests), [frontend component tests](testing_levels.md#frontend-component-tests), and [frontend integration tests](testing_levels.md#frontend-integration-tests).
Winnie Hellmann's avatar
Winnie Hellmann включено в состав коммита
780

GitLab Bot's avatar
GitLab Bot включено в состав коммита
781
All tests in `spec/javascripts/` will eventually be migrated to `spec/frontend/` (see also [#52483](https://gitlab.com/gitlab-org/gitlab-foss/issues/52483)).
Winnie Hellmann's avatar
Winnie Hellmann включено в состав коммита
782

GitLab Bot's avatar
GitLab Bot включено в состав коммита
783
Before May 2018, `features/` also contained feature tests run by Spinach. These tests were removed from the codebase in May 2018 ([#23036](https://gitlab.com/gitlab-org/gitlab-foss/issues/23036)).
Winnie Hellmann's avatar
Winnie Hellmann включено в состав коммита
784

GitLab Bot's avatar
GitLab Bot включено в состав коммита
785
See also [Notes on testing Vue components](../fe_guide/vue.md#testing-vue-components).
Winnie Hellmann's avatar
Winnie Hellmann включено в состав коммита
786
787
788
789
790
791
792

## Test helpers

### Vuex Helper: `testAction`

We have a helper available to make testing actions easier, as per [official documentation](https://vuex.vuejs.org/guide/testing.html):

Winnie Hellmann's avatar
Winnie Hellmann включено в состав коммита
793
```javascript
Winnie Hellmann's avatar
Winnie Hellmann включено в состав коммита
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
testAction(
  actions.actionName, // action
  { }, // params to be passed to action
  state, // state
  [
    { type: types.MUTATION},
    { type: types.MUTATION_1, payload: {}},
  ], // mutations committed
  [
    { type: 'actionName', payload: {}},
    { type: 'actionName1', payload: {}},
  ] // actions dispatched
  done,
);
```

GitLab Bot's avatar
GitLab Bot включено в состав коммита
810
Check an example in [spec/javascripts/ide/stores/actions_spec.jsspec/javascripts/ide/stores/actions_spec.js](https://gitlab.com/gitlab-org/gitlab/blob/master/spec/javascripts/ide/stores/actions_spec.js).
Winnie Hellmann's avatar
Winnie Hellmann включено в состав коммита
811
812
813
814
815
816
817
818
819
820

### Vue Helper: `mountComponent`

To make mounting a Vue component easier and more readable, we have a few helpers available in `spec/helpers/vue_mount_component_helper`:

- `createComponentWithStore`
- `mountComponentWithStore`

Examples of usage:

Winnie Hellmann's avatar
Winnie Hellmann включено в состав коммита
821
```javascript
Winnie Hellmann's avatar
Winnie Hellmann включено в состав коммита
822
823
824
825
826
827
828
829
830
beforeEach(() => {
  vm = createComponentWithStore(Component, store);

  vm.$store.state.currentBranchId = 'master';

  vm.$mount();
});
```

Winnie Hellmann's avatar
Winnie Hellmann включено в состав коммита
831
```javascript
Winnie Hellmann's avatar
Winnie Hellmann включено в состав коммита
832
833
834
835
836
837
838
839
840
841
842
beforeEach(() => {
  vm = mountComponentWithStore(Component, {
    el: '#dummy-element',
    store,
    props: { badge },
  });
});
```

Don't forget to clean up:

Winnie Hellmann's avatar
Winnie Hellmann включено в состав коммита
843
```javascript
Winnie Hellmann's avatar
Winnie Hellmann включено в состав коммита
844
845
846
847
848
afterEach(() => {
  vm.$destroy();
});
```

GitLab Bot's avatar
GitLab Bot включено в состав коммита
849
850
851
852
853
854
855
856
857
858
### Wait until axios requests finish

The axios utils mock module located in `spec/frontend/mocks/ce/lib/utils/axios_utils.js` contains two helper methods for Jest tests that spawn HTTP requests.
These are very useful if you don't have a handle to the request's Promise, for example when a Vue component does a request as part of its life cycle.

- `waitFor(url, callback)`: Runs `callback` after a request to `url` finishes (either successfully or unsuccessfully).
- `waitForAll(callback)`: Runs `callback` once all pending requests have finished. If no requests are pending, runs `callback` on the next tick.

Both functions run `callback` on the next tick after the requests finish (using `setImmediate()`), to allow any `.then()` or `.catch()` handlers to run.

Winnie Hellmann's avatar
Winnie Hellmann включено в состав коммита
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
## Testing with older browsers

Some regressions only affect a specific browser version. We can install and test in particular browsers with either Firefox or Browserstack using the following steps:

### Browserstack

[Browserstack](https://www.browserstack.com/) allows you to test more than 1200 mobile devices and browsers.
You can use it directly through the [live app](https://www.browserstack.com/live) or you can install the [chrome extension](https://chrome.google.com/webstore/detail/browserstack/nkihdmlheodkdfojglpcjjmioefjahjb) for easy access.
You can find the credentials on 1Password, under `frontendteam@gitlab.com`.

### Firefox

#### macOS

You can download any older version of Firefox from the releases FTP server, <https://ftp.mozilla.org/pub/firefox/releases/>:

1. From the website, select a version, in this case `50.0.1`.
1. Go to the mac folder.
1. Select your preferred language, you will find the dmg package inside, download it.
1. Drag and drop the application to any other folder but the `Applications` folder.
1. Rename the application to something like `Firefox_Old`.
1. Move the application to the `Applications` folder.
1. Open up a terminal and run `/Applications/Firefox_Old.app/Contents/MacOS/firefox-bin -profilemanager` to create a new profile specific to that Firefox version.
1. Once the profile has been created, quit the app, and run it again like normal. You now have a working older Firefox version.

884
885
886
---

[Return to Testing documentation](index.md)
GitLab Bot's avatar
GitLab Bot включено в состав коммита
887
888
889
890
891
892
893
894
895
896

<!-- URL References -->

[jasmine-focus]: https://jasmine.github.io/2.5/focused_specs.html
[karma]: http://karma-runner.github.io/
[vue-test]: ../fe_guide/vue.md#testing-vue-components
[rspec]: https://github.com/rspec/rspec-rails#feature-specs
[jasmine]: https://jasmine.github.io/
[jest]: https://jestjs.io
[jestspy]: https://jestjs.io/docs/en/jest-object#jestspyonobject-methodname