debian-mirror-gitlab/doc/development/testing_guide/frontend_testing.md

1598 lines
57 KiB
Markdown
Raw Normal View History

2021-01-29 00:20:46 +05:30
---
stage: none
group: unassigned
2022-11-25 23:54:43 +05:30
info: To determine the technical writer assigned to the Stage/Group associated with this page, see https://about.gitlab.com/handbook/product/ux/technical-writing/#assignments
2021-01-29 00:20:46 +05:30
---
2018-03-17 18:26:18 +05:30
# Frontend testing standards and style guidelines
2021-02-22 17:27:13 +05:30
There are two types of test suites encountered while developing frontend code
2021-11-11 11:23:49 +05:30
at GitLab. We use Jest for JavaScript unit and integration testing,
2018-03-17 18:26:18 +05:30
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.
2023-01-13 00:05:48 +05:30
Most of the time, you should use [RSpec](https://github.com/rspec/rspec-rails#feature-specs) for your feature tests. For more information on how to get started with feature tests, see [get started with feature tests](#get-started-with-feature-tests)
2018-03-17 18:26:18 +05:30
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.
2020-03-13 15:44:24 +05:30
## Vue.js testing
2020-05-24 23:13:21 +05:30
If you are looking for a guide on Vue component testing, you can jump right away to this [section](../fe_guide/vue.md#testing-vue-components).
2020-03-13 15:44:24 +05:30
2019-07-07 11:18:12 +05:30
## Jest
2021-02-22 17:27:13 +05:30
We use Jest to write frontend unit and integration tests.
2019-07-07 11:18:12 +05:30
Jest tests can be found in `/spec/frontend` and `/ee/spec/frontend` in EE.
2019-09-30 21:07:59 +05:30
### Limitations of jsdom
2021-11-11 11:23:49 +05:30
Jest uses jsdom instead of a browser for running tests.
2019-09-30 21:07:59 +05:30
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
2020-04-08 14:13:33 +05:30
See also the issue for [support running Jest tests in browsers](https://gitlab.com/gitlab-org/gitlab/-/issues/26982).
2019-09-30 21:07:59 +05:30
2019-07-07 11:18:12 +05:30
### Debugging Jest tests
2021-04-29 21:17:54 +05:30
Running `yarn jest-debug` runs Jest in debug mode, allowing you to debug/inspect as described in the [Jest docs](https://jestjs.io/docs/troubleshooting#tests-are-failing-and-you-don-t-know-why).
2019-07-07 11:18:12 +05:30
### Timeout error
The default timeout for Jest is set in
2021-09-04 01:27:46 +05:30
[`/spec/frontend/test_setup.js`](https://gitlab.com/gitlab-org/gitlab/-/blob/master/spec/frontend/test_setup.js).
2019-07-07 11:18:12 +05:30
2021-02-22 17:27:13 +05:30
If your test exceeds that time, it fails.
2019-07-07 11:18:12 +05:30
If you cannot improve the performance of the tests, you can increase the timeout
2022-08-27 11:52:29 +05:30
for a specific test using [`jest.setTimeout`](https://jestjs.io/docs/27.x/jest-object#jestsettimeouttimeout)
2019-07-07 11:18:12 +05:30
```javascript
describe('Component', () => {
it('does something amazing', () => {
2022-08-27 11:52:29 +05:30
jest.setTimeout(500);
2019-07-07 11:18:12 +05:30
// ...
});
});
```
Remember that the performance of each test depends on the environment.
2021-04-29 21:17:54 +05:30
### Test-specific stylesheets
To help facilitate RSpec integration tests we have two test-specific stylesheets. These can be used to do things like disable animations to improve test speed, or to make elements visible when they need to be targeted by Capybara click events:
- `app/assets/stylesheets/disable_animations.scss`
- `app/assets/stylesheets/test_environment.scss`
Because the test environment should match the production environment as much as possible, use these minimally and only add to them when necessary.
2020-03-13 15:44:24 +05:30
## What and how to test
2019-10-12 21:52:04 +05:30
2020-03-13 15:44:24 +05:30
Before jumping into more gritty details about Jest-specific workflows like mocks and spies, we should briefly cover what to test with Jest.
2019-09-30 21:07:59 +05:30
2020-03-13 15:44:24 +05:30
### Don't test the library
2019-09-30 21:07:59 +05:30
2020-03-13 15:44:24 +05:30
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
2019-09-30 21:07:59 +05:30
2020-03-13 15:44:24 +05:30
```javascript
import { convertToFahrenheit } from 'temperatureLibrary'
2019-09-30 21:07:59 +05:30
2020-03-13 15:44:24 +05:30
function getFahrenheit(celsius) {
return convertToFahrenheit(celsius)
}
```
2019-10-12 21:52:04 +05:30
2023-03-04 22:38:38 +05:30
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.
2019-09-30 21:07:59 +05:30
2020-03-13 15:44:24 +05:30
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.
2019-09-30 21:07:59 +05:30
2020-03-13 15:44:24 +05:30
```javascript
2021-04-17 20:07:23 +05:30
// Component script
2020-03-13 15:44:24 +05:30
{
computed: {
hasMetricTypes() {
return this.metricTypes.length;
},
}
```
2019-09-30 21:07:59 +05:30
2021-04-17 20:07:23 +05:30
```html
<!-- Component template -->
<template>
<gl-dropdown v-if="hasMetricTypes">
<!-- Dropdown content -->
</gl-dropdown>
</template>
```
Testing the `hasMetricTypes` computed prop would seem like a given here. 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. It's better to test a component in the way the user interacts with it: checking the rendered template.
2019-10-12 21:52:04 +05:30
2020-03-13 15:44:24 +05:30
```javascript
2021-04-17 20:07:23 +05:30
// Bad
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);
2020-03-13 15:44:24 +05:30
});
2021-04-17 20:07:23 +05:30
});
2020-03-13 15:44:24 +05:30
});
2019-09-30 21:07:59 +05:30
2021-04-17 20:07:23 +05:30
// Good
it('displays a dropdown if metricTypes exist', () => {
factory({ metricTypes });
expect(wrapper.findComponent(GlDropdown).exists()).toBe(true);
});
it('does not display a dropdown if no metricTypes exist', () => {
factory();
expect(wrapper.findComponent(GlDropdown).exists()).toBe(false);
});
```
2019-10-12 21:52:04 +05:30
2021-11-18 22:05:49 +05:30
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. A suggestion here is: if you are checking a `wrapper.vm` property, you should probably stop and rethink the test to check the rendered template instead.
2019-09-30 21:07:59 +05:30
2020-03-13 15:44:24 +05:30
Some more examples can be found in the [Frontend unit tests section](testing_levels.md#frontend-unit-tests)
2019-09-30 21:07:59 +05:30
2020-03-13 15:44:24 +05:30
### Don't test your mock
2019-12-26 22:10:19 +05:30
2020-03-13 15:44:24 +05:30
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.
2019-12-26 22:10:19 +05:30
2020-03-13 15:44:24 +05:30
```javascript
const spy = jest.spyOn(idGenerator, 'create')
spy.mockImplementation = () = '1234'
2019-12-26 22:10:19 +05:30
2020-10-24 23:57:45 +05:30
// Bad
2020-03-13 15:44:24 +05:30
expect(idGenerator.create()).toBe('1234')
2019-12-26 22:10:19 +05:30
2020-10-24 23:57:45 +05:30
// Good: actually focusing on the logic of your component and just leverage the controllable mocks output
2020-03-13 15:44:24 +05:30
expect(wrapper.find('div').html()).toBe('<div id="1234">...</div>')
```
2019-12-26 22:10:19 +05:30
2020-03-13 15:44:24 +05:30
### Follow the user
2019-12-26 22:10:19 +05:30
2020-03-13 15:44:24 +05:30
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:
2019-12-26 22:10:19 +05:30
2020-03-13 15:44:24 +05:30
- 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
2018-03-17 18:26:18 +05:30
2020-03-13 15:44:24 +05:30
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.
2018-03-17 18:26:18 +05:30
2020-03-13 15:44:24 +05:30
## Common practices
2018-03-17 18:26:18 +05:30
2021-02-22 17:27:13 +05:30
These some general common practices included as part of our test suite. Should you stumble over something not following this guide, ideally fix it right away. 🎉
2020-03-13 15:44:24 +05:30
### How to query DOM elements
2018-03-17 18:26:18 +05:30
2020-10-24 23:57:45 +05:30
When it comes to querying DOM elements in your tests, it is best to uniquely and semantically target
the element.
2021-02-22 17:27:13 +05:30
Preferentially, this is done by targeting what the user actually sees using [DOM Testing Library](https://testing-library.com/docs/dom-testing-library/intro/).
2021-09-30 23:02:18 +05:30
When selecting by text it is best to use the [`byRole`](https://testing-library.com/docs/queries/byrole/) query
as it helps enforce accessibility best practices. `findByRole` and the other [DOM Testing Library queries](https://testing-library.com/docs/queries/about/) are available when using [`shallowMountExtended` or `mountExtended`](#shallowmountextended-and-mountextended).
2018-03-17 18:26:18 +05:30
2021-01-29 00:20:46 +05:30
When writing Vue component unit tests, it can be wise to query children by component, so that the unit test can focus on comprehensive value coverage
rather than dealing with the complexity of a child component's behavior.
Sometimes, neither of the above are feasible. In these cases, adding test attributes to simplify the selectors might be the best option. A list of
possible selectors include:
2020-04-22 19:07:51 +05:30
2020-06-23 00:09:42 +05:30
- A semantic attribute like `name` (also verifies that `name` was setup properly)
2020-04-22 19:07:51 +05:30
- A `data-testid` attribute ([recommended by maintainers of `@vue/test-utils`](https://github.com/vuejs/vue-test-utils/issues/1498#issuecomment-610133465))
2021-04-29 21:17:54 +05:30
optionally combined with [`shallowMountExtended` or `mountExtended`](#shallowmountextended-and-mountextended)
2020-04-22 19:07:51 +05:30
- a Vue `ref` (if using `@vue/test-utils`)
2020-03-13 15:44:24 +05:30
```javascript
2021-04-29 21:17:54 +05:30
import { shallowMountExtended } from 'helpers/vue_test_utils_helper'
const wrapper = shallowMountExtended(ExampleComponent);
2020-10-24 23:57:45 +05:30
it('exists', () => {
2021-01-29 00:20:46 +05:30
// Best (especially for integration tests)
2021-04-29 21:17:54 +05:30
wrapper.findByRole('link', { name: /Click Me/i })
wrapper.findByRole('link', { name: 'Click Me' })
wrapper.findByText('Click Me')
wrapper.findByText(/Click Me/i)
2021-01-29 00:20:46 +05:30
// Good (especially for unit tests)
2021-09-04 01:27:46 +05:30
wrapper.findComponent(FooComponent);
2020-10-24 23:57:45 +05:30
wrapper.find('input[name=foo]');
2021-02-22 17:27:13 +05:30
wrapper.find('[data-testid="my-foo-id"]');
2021-04-29 21:17:54 +05:30
wrapper.findByTestId('my-foo-id'); // with shallowMountExtended or mountExtended check below
2020-10-24 23:57:45 +05:30
wrapper.find({ ref: 'foo'});
// Bad
wrapper.find('.js-foo');
wrapper.find('.btn-primary');
wrapper.find('.qa-foo-component');
wrapper.find('[data-qa-selector="foo"]');
});
2020-03-13 15:44:24 +05:30
```
2021-02-22 17:27:13 +05:30
It is recommended to use `kebab-case` for `data-testid` attribute.
2020-03-13 15:44:24 +05:30
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.
2020-10-24 23:57:45 +05:30
### Querying for child components
When testing Vue components with `@vue/test-utils` another possible approach is querying for child
components instead of querying for DOM nodes. This assumes that implementation details of behavior
under test should be covered by that component's individual unit test. There is no strong preference
in writing DOM or component queries as long as your tests reliably cover expected behavior for the
component under test.
Example:
```javascript
it('exists', () => {
2021-09-04 01:27:46 +05:30
wrapper.findComponent(FooComponent);
2020-10-24 23:57:45 +05:30
});
```
2020-03-13 15:44:24 +05:30
### Naming unit tests
2018-03-17 18:26:18 +05:30
When writing describe test blocks to test specific functions/methods,
2021-03-11 19:13:27 +05:30
use the method name as the describe block name.
2018-03-17 18:26:18 +05:30
2020-10-24 23:57:45 +05:30
**Bad**:
2018-03-17 18:26:18 +05:30
```javascript
2020-10-24 23:57:45 +05:30
describe('#methodName', () => {
2018-03-17 18:26:18 +05:30
it('passes', () => {
expect(true).toEqual(true);
});
});
2020-10-24 23:57:45 +05:30
describe('.methodName', () => {
2018-03-17 18:26:18 +05:30
it('passes', () => {
expect(true).toEqual(true);
});
});
2020-10-24 23:57:45 +05:30
```
2018-03-17 18:26:18 +05:30
2020-10-24 23:57:45 +05:30
**Good**:
```javascript
describe('methodName', () => {
2018-03-17 18:26:18 +05:30
it('passes', () => {
expect(true).toEqual(true);
});
});
```
2018-10-15 14:42:47 +05:30
2020-03-13 15:44:24 +05:30
### Testing promises
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 () => {
2020-11-24 15:15:51 +05:30
await expect(user.getUserName(1)).rejects.toThrow('User with 1 not found.');
2020-03-13 15:44:24 +05:30
});
```
2018-03-17 18:26:18 +05:30
2022-11-25 23:54:43 +05:30
You can also return a promise from the test function.
2020-11-24 15:15:51 +05:30
Using the `done` and `done.fail` callbacks is discouraged when working with
2022-07-16 23:28:13 +05:30
promises. They should not be used.
2018-03-17 18:26:18 +05:30
2020-10-24 23:57:45 +05:30
**Bad**:
2018-03-17 18:26:18 +05:30
```javascript
2020-11-24 15:15:51 +05:30
// missing return
2020-10-24 23:57:45 +05:30
it('tests a promise', () => {
promise.then(data => {
expect(data).toBe(asExpected);
});
});
2020-11-24 15:15:51 +05:30
// uses done/done.fail
2020-10-24 23:57:45 +05:30
it('tests a promise', done => {
2018-03-17 18:26:18 +05:30
promise
2020-10-24 23:57:45 +05:30
.then(data => {
expect(data).toBe(asExpected);
2018-03-17 18:26:18 +05:30
})
.then(done)
2020-11-24 15:15:51 +05:30
.catch(done.fail);
2018-03-17 18:26:18 +05:30
});
2020-10-24 23:57:45 +05:30
```
2018-03-17 18:26:18 +05:30
2020-10-24 23:57:45 +05:30
**Good**:
```javascript
2020-11-24 15:15:51 +05:30
// verifying a resolved promise
it('tests a promise', () => {
return promise
2018-10-15 14:42:47 +05:30
.then(data => {
2018-03-17 18:26:18 +05:30
expect(data).toBe(asExpected);
2020-11-24 15:15:51 +05:30
});
2018-03-17 18:26:18 +05:30
});
2020-11-24 15:15:51 +05:30
// verifying a resolved promise using Jest's `resolves` matcher
it('tests a promise', () => {
return expect(promise).resolves.toBe(asExpected);
});
// verifying a rejected promise using Jest's `rejects` matcher
it('tests a promise rejection', () => {
return expect(promise).rejects.toThrow(expectedError);
2018-03-17 18:26:18 +05:30
});
```
2020-03-13 15:44:24 +05:30
### Manipulating Time
2018-10-15 14:42:47 +05:30
2021-02-22 17:27:13 +05:30
Sometimes we have to test time-sensitive code. For example, recurring events that run every X amount of seconds or similar. Here are some strategies to deal with that:
2018-10-15 14:42:47 +05:30
2020-03-13 15:44:24 +05:30
#### `setTimeout()` / `setInterval()` in application
2018-10-15 14:42:47 +05:30
2020-03-13 15:44:24 +05:30
If the application itself is waiting for some time, mock await the waiting. In Jest this is already
2021-09-04 01:27:46 +05:30
[done by default](https://gitlab.com/gitlab-org/gitlab/-/blob/a2128edfee799e49a8732bfa235e2c5e14949c68/jest.config.js#L47)
2021-11-11 11:23:49 +05:30
(see also [Jest Timer Mocks](https://jestjs.io/docs/timer-mocks)).
2018-10-15 14:42:47 +05:30
2020-03-13 15:44:24 +05:30
```javascript
const doSomethingLater = () => {
setTimeout(() => {
// do something
}, 4000);
};
2019-07-07 11:18:12 +05:30
```
2019-09-04 21:01:54 +05:30
2020-03-13 15:44:24 +05:30
**in Jest:**
2018-03-17 18:26:18 +05:30
2020-03-13 15:44:24 +05:30
```javascript
it('does something', () => {
doSomethingLater();
jest.runAllTimers();
2018-10-15 14:42:47 +05:30
2020-03-13 15:44:24 +05:30
expect(something).toBe('done');
2018-10-15 14:42:47 +05:30
});
```
2021-10-27 15:23:28 +05:30
### Mocking the current location in Jest
NOTE:
The value of `window.location.href` is reset before every test to avoid earlier
tests affecting later ones.
If your tests require `window.location.href` to take a particular value, use
the `setWindowLocation` helper:
```javascript
import setWindowLocation from 'helpers/set_window_location';
it('passes', () => {
setWindowLocation('https://gitlab.test/foo?bar=true');
expect(window.location).toMatchObject({
hostname: 'gitlab.test',
pathname: '/foo',
search: '?bar=true',
});
});
```
To modify only the hash, use either the `setWindowLocation` helper, or assign
2022-01-26 12:08:38 +05:30
directly to `window.location.hash`, for example:
2021-10-27 15:23:28 +05:30
```javascript
it('passes', () => {
window.location.hash = '#foo';
expect(window.location.href).toBe('http://test.host/#foo');
});
```
If your tests need to assert that certain `window.location` methods were
called, use the `useMockLocationHelper` helper:
```javascript
import { useMockLocationHelper } from 'helpers/mock_window_location_helper';
useMockLocationHelper();
it('passes', () => {
window.location.reload();
expect(window.location.reload).toHaveBeenCalled();
});
```
2020-03-13 15:44:24 +05:30
### Waiting in tests
2018-11-18 11:00:15 +05:30
2019-09-04 21:01:54 +05:30
Sometimes a test needs to wait for something to happen in the application before it continues.
2022-10-11 01:57:18 +05:30
You should try to avoid:
- [`setTimeout`](https://developer.mozilla.org/en-US/docs/Web/API/setTimeout) because it makes the reason for waiting unclear. Additionally, it is faked in our tests so its usage is tricky.
- [`setImmediate`](https://developer.mozilla.org/en-US/docs/Web/API/Window/setImmediate) because it is no longer supported in Jest 27 and later. See [this epic](https://gitlab.com/groups/gitlab-org/-/epics/7002) for details.
2019-09-04 21:01:54 +05:30
2020-03-13 15:44:24 +05:30
#### Promises and Ajax calls
2019-09-04 21:01:54 +05:30
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
2020-03-13 15:44:24 +05:30
it('waits for an Ajax call', async () => {
await askTheServer()
expect(something).toBe('done');
2019-09-04 21:01:54 +05:30
});
```
2022-10-11 01:57:18 +05:30
If you cannot register handlers to the `Promise`, for example because it is executed in a synchronous Vue lifecycle hook, take a look at the [`waitFor`](#wait-until-axios-requests-finish) helpers or flush all pending `Promise`s with:
2019-09-04 21:01:54 +05:30
**in Jest:**
```javascript
2022-10-11 01:57:18 +05:30
it('waits for an Ajax call', async () => {
2019-09-04 21:01:54 +05:30
synchronousFunction();
2023-01-13 00:05:48 +05:30
2022-10-11 01:57:18 +05:30
await waitForPromises();
2019-09-04 21:01:54 +05:30
expect(something).toBe('done');
});
```
2020-03-13 15:44:24 +05:30
#### Vue rendering
2019-09-04 21:01:54 +05:30
2022-08-27 11:52:29 +05:30
Use [`nextTick()`](https://v2.vuejs.org/v2/api/#Vue-nextTick) to wait until a Vue component is
2022-07-16 23:28:13 +05:30
re-rendered.
2019-09-04 21:01:54 +05:30
**in Jest:**
```javascript
2022-07-16 23:28:13 +05:30
import { nextTick } from 'vue';
// ...
it('renders something', async () => {
2019-09-04 21:01:54 +05:30
wrapper.setProps({ value: 'new value' });
2022-07-16 23:28:13 +05:30
await nextTick();
expect(wrapper.text()).toBe('new value');
2019-09-04 21:01:54 +05:30
});
```
2020-03-13 15:44:24 +05:30
#### Events
2019-09-04 21:01:54 +05:30
If the application triggers an event that you need to wait for in your test, register an event handler which contains
the assertions:
```javascript
2022-07-16 23:28:13 +05:30
it('waits for an event', () => {
2019-09-04 21:01:54 +05:30
eventHub.$once('someEvent', eventHandler);
someFunction();
2022-07-16 23:28:13 +05:30
return new Promise((resolve) => {
function expectEventHandler() {
expect(something).toBe('done');
resolve();
}
});
2019-09-04 21:01:54 +05:30
});
```
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');
});
});
```
2018-11-18 11:00:15 +05:30
2023-05-27 22:25:52 +05:30
### Manipulate `gon` object
`gon` (or `window.gon`) is a global object used to pass data from the backend. If your test depends
on its value you can directly modify it:
```javascript
describe('when logged in', () => {
beforeEach(() => {
gon.current_user_id = 1;
});
it('shows message', () => {
expect(wrapper.text()).toBe('Logged in!');
});
})
```
`gon` is reset in every test to ensure tests are isolated.
2020-03-13 15:44:24 +05:30
### Ensuring that tests are isolated
2019-12-26 22:10:19 +05:30
2023-03-04 22:38:38 +05:30
Tests are normally architected in a pattern which requires a recurring setup of the component under test. This is often achieved by making use of the `beforeEach` hook.
2019-12-26 22:10:19 +05:30
Example
```javascript
let wrapper;
beforeEach(() => {
wrapper = mount(Component);
});
2023-03-04 22:38:38 +05:30
```
With [enableAutoDestroy](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/100389), it is no longer necessary to manually call `wrapper.destroy()`.
However, some mocks, spies, and fixtures do need to be torn down, and we can leverage the `afterEach` hook.
Example
```javascript
let wrapper;
2019-12-26 22:10:19 +05:30
afterEach(() => {
2023-03-04 22:38:38 +05:30
fakeApollo = null;
store = null;
2019-12-26 22:10:19 +05:30
});
```
2020-07-28 23:09:34 +05:30
### Jest best practices
> [Introduced](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/34209) in GitLab 13.2.
#### Prefer `toBe` over `toEqual` when comparing primitive values
2021-04-29 21:17:54 +05:30
Jest has [`toBe`](https://jestjs.io/docs/expect#tobevalue) and
[`toEqual`](https://jestjs.io/docs/expect#toequalvalue) matchers.
As [`toBe`](https://jestjs.io/docs/expect#tobevalue) uses
2020-07-28 23:09:34 +05:30
[`Object.is`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is)
to compare values, it's faster (by default) than using `toEqual`.
2021-02-22 17:27:13 +05:30
While the latter eventually falls back to leverage [`Object.is`](https://github.com/facebook/jest/blob/master/packages/expect/src/jasmineUtils.ts#L91),
2020-07-28 23:09:34 +05:30
for primitive values, it should only be used when complex objects need a comparison.
Examples:
```javascript
const foo = 1;
2020-10-24 23:57:45 +05:30
// Bad
2020-07-28 23:09:34 +05:30
expect(foo).toEqual(1);
2020-10-24 23:57:45 +05:30
// Good
expect(foo).toBe(1);
2020-07-28 23:09:34 +05:30
```
#### Prefer more befitting matchers
Jest provides useful matchers like `toHaveLength` or `toBeUndefined` to make your tests more
readable and to produce more understandable error messages. Check their docs for the
2021-04-29 21:17:54 +05:30
[full list of matchers](https://jestjs.io/docs/expect#methods).
2020-07-28 23:09:34 +05:30
Examples:
```javascript
const arr = [1, 2];
// prints:
// Expected length: 1
// Received length: 2
expect(arr).toHaveLength(1);
// prints:
// Expected: 1
// Received: 2
expect(arr.length).toBe(1);
// prints:
// expect(received).toBe(expected) // Object.is equality
// Expected: undefined
// Received: "bar"
const foo = 'bar';
expect(foo).toBe(undefined);
// prints:
// expect(received).toBeUndefined()
// Received: "bar"
const foo = 'bar';
expect(foo).toBeUndefined();
```
#### Avoid using `toBeTruthy` or `toBeFalsy`
Jest also provides following matchers: `toBeTruthy` and `toBeFalsy`. We should not use them because
they make tests weaker and produce false-positive results.
For example, `expect(someBoolean).toBeFalsy()` passes when `someBoolean === null`, and when
`someBoolean === false`.
#### Tricky `toBeDefined` matcher
Jest has the tricky `toBeDefined` matcher that can produce false positive test. Because it
[validates](https://github.com/facebook/jest/blob/master/packages/expect/src/matchers.ts#L204)
the given value for `undefined` only.
```javascript
2020-10-24 23:57:45 +05:30
// Bad: if finder returns null, the test will pass
2020-07-28 23:09:34 +05:30
expect(wrapper.find('foo')).toBeDefined();
2020-10-24 23:57:45 +05:30
// Good
expect(wrapper.find('foo').exists()).toBe(true);
2020-07-28 23:09:34 +05:30
```
#### Avoid using `setImmediate`
Try to avoid using `setImmediate`. `setImmediate` is an ad-hoc solution to run your callback after
the I/O completes. And it's not part of the Web API, hence, we target NodeJS environments in our
unit tests.
Instead of `setImmediate`, use `jest.runAllTimers` or `jest.runOnlyPendingTimers` to run pending timers.
The latter is useful when you have `setInterval` in the code. **Remember:** our Jest configuration uses fake timers.
2020-10-04 03:57:07 +05:30
## Avoid non-deterministic specs
Non-determinism is the breeding ground for flaky and brittle specs. Such specs end up breaking the CI pipeline, interrupting the work flow of other contributors.
2022-01-26 12:08:38 +05:30
1. Make sure your test subject's collaborators (for example, Axios, Apollo, Lodash helpers) and test environment (for example, Date) behave consistently across systems and over time.
1. Make sure tests are focused and not doing "extra work" (for example, needlessly creating the test subject more than once in an individual test).
2020-10-04 03:57:07 +05:30
### Faking `Date` for determinism
2021-03-11 19:13:27 +05:30
`Date` is faked by default in our Jest environment. This means every call to `Date()` or `Date.now()` returns a fixed deterministic value.
If you really need to change the default fake date, you can call `useFakeDate` within any `describe` block, and
the date will be replaced for that specs within that `describe` context only:
2020-10-04 03:57:07 +05:30
```javascript
import { useFakeDate } from 'helpers/fake_date';
describe('cool/component', () => {
2021-03-11 19:13:27 +05:30
// Default fake `Date`
const TODAY = new Date();
2020-10-04 03:57:07 +05:30
2022-01-26 12:08:38 +05:30
// NOTE: `useFakeDate` cannot be called during test execution (that is, inside `it`, `beforeEach`, `beforeAll`, etc.).
2021-03-11 19:13:27 +05:30
describe("on Ada Lovelace's Birthday", () => {
useFakeDate(1815, 11, 10)
it('Date is no longer default', () => {
expect(new Date()).not.toEqual(TODAY);
});
});
it('Date is still default in this scope', () => {
expect(new Date()).toEqual(TODAY)
});
})
```
Similarly, if you really need to use the real `Date` class, then you can import and call `useRealDate` within any `describe` block:
```javascript
import { useRealDate } from 'helpers/fake_date';
2022-01-26 12:08:38 +05:30
// NOTE: `useRealDate` cannot be called during test execution (that is, inside `it`, `beforeEach`, `beforeAll`, etc.).
2021-03-11 19:13:27 +05:30
describe('with real date', () => {
useRealDate();
2020-10-04 03:57:07 +05:30
});
```
### Faking `Math.random` for determinism
Consider replacing `Math.random` with a fake when the test subject depends on it.
```javascript
beforeEach(() => {
// https://xkcd.com/221/
jest.spyOn(Math, 'random').mockReturnValue(0.4);
});
```
2020-03-13 15:44:24 +05:30
## Factories
TBU
## Mocking Strategies with Jest
### Stubbing and Mocking
2020-05-24 23:13:21 +05:30
Stubs or spies are often used synonymously. In Jest it's quite easy thanks to the `.spyOn` method.
2021-04-29 21:17:54 +05:30
[Official docs](https://jestjs.io/docs/jest-object#jestspyonobject-methodname)
2020-03-13 15:44:24 +05:30
The more challenging part are mocks, which can be used for functions or even dependencies.
### Manual module mocks
2020-04-22 19:07:51 +05:30
Manual mocks are used to mock modules across the entire Jest environment. This is a very powerful testing tool that helps simplify
2022-01-26 12:08:38 +05:30
unit testing by mocking out modules that cannot be easily consumed in our test environment.
2019-07-07 11:18:12 +05:30
2022-01-26 12:08:38 +05:30
> **WARNING:** Do not use manual mocks if a mock should not be consistently applied in every spec (that is, it's only needed by a few specs).
2021-04-29 21:17:54 +05:30
> Instead, consider using [`jest.mock(..)`](https://jestjs.io/docs/jest-object#jestmockmodulename-factory-options)
2020-04-22 19:07:51 +05:30
> (or a similar mocking function) in the relevant spec file.
2019-07-07 11:18:12 +05:30
2023-03-04 22:38:38 +05:30
#### Where should you put manual mocks?
2019-07-07 11:18:12 +05:30
2021-04-29 21:17:54 +05:30
Jest supports [manual module mocks](https://jestjs.io/docs/manual-mocks) by placing a mock in a `__mocks__/` directory next to the source module
2022-01-26 12:08:38 +05:30
(for example, `app/assets/javascripts/ide/__mocks__`). **Don't do this.** We want to keep all of our test-related code in one place (the `spec/` folder).
2018-03-17 18:26:18 +05:30
2021-03-11 19:13:27 +05:30
If a manual mock is needed for a `node_modules` package, use the `spec/frontend/__mocks__` folder. Here's an example of
2021-09-04 01:27:46 +05:30
a [Jest mock for the package `monaco-editor`](https://gitlab.com/gitlab-org/gitlab/-/blob/b7f914cddec9fc5971238cdf12766e79fa1629d7/spec/frontend/__mocks__/monaco-editor/index.js#L1).
2018-03-17 18:26:18 +05:30
2022-01-26 12:08:38 +05:30
If a manual mock is needed for a CE module, place the implementation in
`spec/frontend/__helpers__/mocks` and add a line to the `frontend/test_setup`
(or the `frontend/shared_test_setup`) that looks something like:
2020-03-13 15:44:24 +05:30
2022-01-26 12:08:38 +05:30
```javascript
// "~/lib/utils/axios_utils" is the path to the real module
// "helpers/mocks/axios_utils" is the path to the mocked implementation
jest.mock('~/lib/utils/axios_utils', () => jest.requireActual('helpers/mocks/axios_utils'));
```
2020-03-13 15:44:24 +05:30
2020-04-22 19:07:51 +05:30
#### Manual mock examples
2020-03-13 15:44:24 +05:30
2022-01-26 12:08:38 +05:30
- [`__helpers__/mocks/axios_utils`](https://gitlab.com/gitlab-org/gitlab/-/blob/a50edd12b3b1531389624086b6381a042c8143ef/spec/frontend/__helpers__/mocks/axios_utils.js#L1) -
2020-04-22 19:07:51 +05:30
This mock is helpful because we don't want any unmocked requests to pass any tests. Also, we are able to inject some test helpers such as `axios.waitForAll`.
2021-09-04 01:27:46 +05:30
- [`__mocks__/mousetrap/index.js`](https://gitlab.com/gitlab-org/gitlab/-/blob/cd4c086d894226445be9d18294a060ba46572435/spec/frontend/__mocks__/mousetrap/index.js#L1) -
2020-06-23 00:09:42 +05:30
This mock is helpful because the module itself uses AMD format which webpack understands, but is incompatible with the jest environment. This mock doesn't remove
2020-04-22 19:07:51 +05:30
any behavior, only provides a nice es6 compatible wrapper.
2021-09-04 01:27:46 +05:30
- [`__mocks__/monaco-editor/index.js`](https://gitlab.com/gitlab-org/gitlab/-/blob/b7f914cddec9fc5971238cdf12766e79fa1629d7/spec/frontend/__mocks__/monaco-editor/index.js) -
2020-06-23 00:09:42 +05:30
This mock is helpful because the Monaco package is completely incompatible in a Jest environment. In fact, webpack requires a special loader to make it work. This mock
2021-04-29 21:17:54 +05:30
makes this package consumable by Jest.
2020-03-13 15:44:24 +05:30
### Keep mocks light
2020-04-22 19:07:51 +05:30
Global mocks introduce magic and technically can reduce test coverage. When mocking is deemed profitable:
- Keep the mock short and focused.
2021-03-11 19:13:27 +05:30
- Leave a top-level comment in the mock on why it is necessary.
2020-04-22 19:07:51 +05:30
### Additional mocking techniques
2020-03-13 15:44:24 +05:30
2021-04-29 21:17:54 +05:30
Consult the [official Jest docs](https://jestjs.io/docs/jest-object#mock-modules) for a full overview of the available mocking features.
2020-03-13 15:44:24 +05:30
## Running Frontend Tests
2018-03-17 18:26:18 +05:30
2022-04-04 11:22:00 +05:30
Before generating fixtures, make sure you have a running GDK instance.
2019-07-07 11:18:12 +05:30
For running the frontend tests, you need the following commands:
2018-03-17 18:26:18 +05:30
2021-02-22 17:27:13 +05:30
- `rake frontend:fixtures` (re-)generates [fixtures](#frontend-test-fixtures). Make sure that
fixtures are up-to-date before running tests that require them.
- `yarn jest` runs Jest tests.
2018-03-17 18:26:18 +05:30
2020-03-13 15:44:24 +05:30
### Live testing and focused testing -- Jest
2020-06-23 00:09:42 +05:30
While you work on a test suite, you may want to run these specs in watch mode, so they rerun automatically on every save.
2020-03-13 15:44:24 +05:30
```shell
# Watch and rerun all specs matching the name icon
yarn jest --watch icon
2021-01-29 00:20:46 +05:30
# Watch and rerun one specific file
2020-03-13 15:44:24 +05:30
yarn jest --watch path/to/spec/file.spec.js
```
You can also run some focused tests without the `--watch` flag
```shell
# 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
```
2021-11-11 11:23:49 +05:30
## Frontend test fixtures
2018-03-17 18:26:18 +05:30
2021-11-11 11:23:49 +05:30
Frontend fixtures are files containing responses from backend controllers. These responses can be either HTML
generated from HAML templates or JSON payloads. Frontend tests that rely on these responses are
often using fixtures to validate correct integration with the backend code.
2020-03-13 15:44:24 +05:30
2021-11-11 11:23:49 +05:30
### Use fixtures
2018-03-17 18:26:18 +05:30
2021-11-18 22:05:49 +05:30
To import a JSON fixture, `import` it using the `test_fixtures` alias.
2018-10-15 14:42:47 +05:30
2021-11-11 11:23:49 +05:30
```javascript
2021-11-18 22:05:49 +05:30
import responseBody from 'test_fixtures/some/fixture.json' // loads spec/frontend/fixtures/some/fixture.json
2021-11-11 11:23:49 +05:30
it('makes a request', () => {
axiosMock.onGet(endpoint).reply(200, responseBody);
2018-10-15 14:42:47 +05:30
2021-11-11 11:23:49 +05:30
myButton.click();
2018-10-15 14:42:47 +05:30
2021-11-11 11:23:49 +05:30
// ...
});
2021-11-18 22:05:49 +05:30
```
For other fixtures, Jest uses `spec/frontend/__helpers__/fixtures.js` to import them in tests.
2018-10-15 14:42:47 +05:30
2021-11-18 22:05:49 +05:30
The following are examples of tests that work for Jest:
```javascript
2021-11-11 11:23:49 +05:30
it('uses some HTML element', () => {
2022-07-16 23:28:13 +05:30
loadHTMLFixture('some/page.html'); // loads spec/frontend/fixtures/some/page.html and adds it to the DOM
2019-09-04 21:01:54 +05:30
2021-11-11 11:23:49 +05:30
const element = document.getElementById('#my-id');
// ...
2022-07-16 23:28:13 +05:30
// Jest does not clean up the DOM automatically
resetHTMLFixture();
2021-11-11 11:23:49 +05:30
});
```
2020-10-24 23:57:45 +05:30
### Generate fixtures
You can find code to generate test fixtures in:
2019-09-04 21:01:54 +05:30
2019-10-12 21:52:04 +05:30
- `spec/frontend/fixtures/`, for running tests in CE.
- `ee/spec/frontend/fixtures/`, for running tests in EE.
2019-09-04 21:01:54 +05:30
2020-10-24 23:57:45 +05:30
You can generate fixtures by running:
- `bin/rake frontend:fixtures` to generate all fixtures
- `bin/rspec spec/frontend/fixtures/merge_requests.rb` to generate specific fixtures (in this case for `merge_request.rb`)
You can find generated fixtures are in `tmp/tests/frontend/fixtures-ee`.
#### Creating new fixtures
For each fixture, you can find the content of the `response` variable in the output file.
2021-02-22 17:27:13 +05:30
For example, a test named `"merge_requests/diff_discussion.json"` in `spec/frontend/fixtures/merge_requests.rb`
produces an output file `tmp/tests/frontend/fixtures-ee/merge_requests/diff_discussion.json`.
2020-10-24 23:57:45 +05:30
The `response` variable gets automatically set if the test is marked as `type: :request` or `type: :controller`.
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/`.
2021-03-08 18:12:59 +05:30
##### GraphQL query fixtures
You can create a fixture that represents the result of a GraphQL query using the `get_graphql_query_as_string`
helper method. For example:
```ruby
# spec/frontend/fixtures/releases.rb
describe GraphQL::Query, type: :request do
include GraphqlHelpers
2021-06-08 01:23:25 +05:30
all_releases_query_path = 'releases/graphql/queries/all_releases.query.graphql'
2021-03-08 18:12:59 +05:30
it "graphql/#{all_releases_query_path}.json" do
2021-09-30 23:02:18 +05:30
query = get_graphql_query_as_string(all_releases_query_path)
2021-03-08 18:12:59 +05:30
post_graphql(query, current_user: admin, variables: { fullPath: project.full_path })
expect_graphql_errors_to_be_empty
end
end
```
This will create a new fixture located at
2021-06-08 01:23:25 +05:30
`tmp/tests/frontend/fixtures-ee/graphql/releases/graphql/queries/all_releases.query.graphql.json`.
2021-03-08 18:12:59 +05:30
2021-11-18 22:05:49 +05:30
You can import the JSON fixture in a Jest test using the `test_fixtures` alias
2022-10-11 01:57:18 +05:30
[as described previously](#use-fixtures).
2021-03-08 18:12:59 +05:30
2020-03-13 15:44:24 +05:30
## Data-driven tests
Similar to [RSpec's parameterized tests](best_practices.md#table-based--parameterized-tests),
Jest supports data-driven tests for:
2021-04-29 21:17:54 +05:30
- Individual tests using [`test.each`](https://jestjs.io/docs/api#testeachtable-name-fn-timeout) (aliased to `it.each`).
- Groups of tests using [`describe.each`](https://jestjs.io/docs/api#describeeachtable-name-fn-timeout).
2020-03-13 15:44:24 +05:30
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)
}
);
```
2021-03-11 19:13:27 +05:30
NOTE:
Only use template literal block if pretty print is not needed for spec output. For example, empty strings, nested objects etc.
2021-01-29 00:20:46 +05:30
2022-01-26 12:08:38 +05:30
For example, when testing the difference between an empty search string and a non-empty search string, the use of the array block syntax with the pretty print option would be preferred. That way the differences between an empty string (`''`) and a non-empty string (`'search string'`) would be visible in the spec output. Whereas with a template literal block, the empty string would be shown as a space, which could lead to a confusing developer experience.
2021-01-29 00:20:46 +05:30
```javascript
// bad
it.each`
searchTerm | expected
${''} | ${{ issue: { users: { nodes: [] } } }}
${'search term'} | ${{ issue: { other: { nested: [] } } }}
`('when search term is $searchTerm, it returns $expected', ({ searchTerm, expected }) => {
expect(search(searchTerm)).toEqual(expected)
});
// good
it.each([
['', { issue: { users: { nodes: [] } } }],
['search term', { issue: { other: { nested: [] } } }],
])('when search term is %p, expect to return %p',
(searchTerm, expected) => {
expect(search(searchTerm)).toEqual(expected)
}
);
```
2020-03-13 15:44:24 +05:30
```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)
})
});
```
2018-03-17 18:26:18 +05:30
## Gotchas
### RSpec errors due to JavaScript
2021-02-22 17:27:13 +05:30
By default RSpec unit tests don't run JavaScript in the headless browser
and rely on inspecting the HTML generated by rails.
2018-03-17 18:26:18 +05:30
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
2021-02-22 17:27:13 +05:30
don't do this, the spec runner displays vague error messages.
2018-03-17 18:26:18 +05:30
2023-01-13 00:05:48 +05:30
To enable a JavaScript driver in an `RSpec` test, add `:js` to the
2018-03-17 18:26:18 +05:30
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
```
2021-04-17 20:07:23 +05:30
### Jest test timeout due to asynchronous imports
2021-02-22 17:27:13 +05:30
If a module asynchronously imports some other modules at runtime, these modules must be
transpiled by the Jest loaders at runtime. It's possible that this can cause [Jest to timeout](https://gitlab.com/gitlab-org/gitlab/-/issues/280809).
If you run into this issue, consider eager importing the module so that Jest compiles
and caches it at compile-time, fixing the runtime timeout.
Consider the following example:
```javascript
// the_subject.js
export default {
components: {
// Async import Thing because it is large and isn't always needed.
Thing: () => import(/* webpackChunkName: 'thing' */ './path/to/thing.vue'),
}
};
```
Jest doesn't automatically transpile the `thing.vue` module, and depending on its size, could
cause Jest to time out. We can force Jest to transpile and cache this module by eagerly importing
it like so:
```javascript
// the_subject_spec.js
import Subject from '~/feature/the_subject.vue';
// Force Jest to transpile and cache
2021-11-18 22:05:49 +05:30
// eslint-disable-next-line no-unused-vars
2021-02-22 17:27:13 +05:30
import _Thing from '~/feature/path/to/thing.vue';
```
2021-03-11 19:13:27 +05:30
NOTE:
Do not disregard test timeouts. This could be a sign that there's
2021-02-22 17:27:13 +05:30
actually a production problem. Use this opportunity to analyze the production webpack bundles and
2021-03-11 19:13:27 +05:30
chunks and confirm that there is not a production issue with the asynchronous imports.
2021-02-22 17:27:13 +05:30
2019-12-04 20:38:33 +05:30
## Overview of Frontend Testing Levels
2020-03-13 15:44:24 +05:30
Main information on frontend testing levels can be found in the [Testing Levels page](testing_levels.md).
2019-12-04 20:38:33 +05:30
Tests relevant for frontend development can be found at the following places:
2020-03-13 15:44:24 +05:30
- `spec/frontend/`, for Jest tests
- `spec/features/`, for RSpec tests
2021-11-11 11:23:49 +05:30
RSpec runs complete [feature tests](testing_levels.md#frontend-feature-tests), while the Jest 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).
2019-12-04 20:38:33 +05:30
2020-06-23 00:09:42 +05:30
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)).
2019-12-04 20:38:33 +05:30
2020-04-08 14:13:33 +05:30
See also [Notes on testing Vue components](../fe_guide/vue.md#testing-vue-components).
2019-12-04 20:38:33 +05:30
## Test helpers
2021-09-04 01:27:46 +05:30
Test helpers can be found in [`spec/frontend/__helpers__`](https://gitlab.com/gitlab-org/gitlab/-/blob/master/spec/frontend/__helpers__).
2021-03-11 19:13:27 +05:30
If you introduce new helpers, place them in that directory.
2021-03-08 18:12:59 +05:30
2019-12-04 20:38:33 +05:30
### Vuex Helper: `testAction`
We have a helper available to make testing actions easier, as per [official documentation](https://vuex.vuejs.org/guide/testing.html):
```javascript
2021-11-11 11:23:49 +05:30
// prefer using like this, a single object argument so parameters are obvious from reading the test
await testAction({
action: actions.actionName,
payload: { deleteListId: 1 },
state: { lists: [1, 2, 3] },
expectedMutations: [ { type: types.MUTATION} ],
expectedActions: [],
});
// old way, don't do this for new tests
2019-12-04 20:38:33 +05:30
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,
);
```
2020-06-23 00:09:42 +05:30
### Wait until Axios requests finish
2019-12-04 20:38:33 +05:30
2021-03-11 19:13:27 +05:30
<!-- vale gitlab.Spelling = NO -->
2022-10-11 01:57:18 +05:30
The Axios Utils mock module located in `spec/frontend/__helpers__/mocks/axios_utils.js` contains two helper methods for Jest tests that spawn HTTP requests.
2019-12-04 20:38:33 +05:30
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.
2021-03-11 19:13:27 +05:30
<!-- vale gitlab.Spelling = YES -->
2019-12-04 20:38:33 +05:30
- `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.
2021-04-29 21:17:54 +05:30
### `shallowMountExtended` and `mountExtended`
2021-02-22 17:27:13 +05:30
2021-06-08 01:23:25 +05:30
The `shallowMountExtended` and `mountExtended` utilities provide you with the ability to perform
2021-09-30 23:02:18 +05:30
any of the available [DOM Testing Library queries](https://testing-library.com/docs/queries/about/)
2021-04-29 21:17:54 +05:30
by prefixing them with `find` or `findAll`.
2021-02-22 17:27:13 +05:30
```javascript
2021-04-29 21:17:54 +05:30
import { shallowMountExtended } from 'helpers/vue_test_utils_helper';
2021-02-22 17:27:13 +05:30
describe('FooComponent', () => {
2021-04-29 21:17:54 +05:30
const wrapper = shallowMountExtended({
template: `
<div data-testid="gitlab-frontend-stack">
<p>GitLab frontend stack</p>
<div role="tablist">
<button role="tab" aria-selected="true">Vue.js</button>
<button role="tab" aria-selected="false">GraphQL</button>
<button role="tab" aria-selected="false">SCSS</button>
</div>
</div>
`,
});
it('finds elements with `findByTestId`', () => {
expect(wrapper.findByTestId('gitlab-frontend-stack').exists()).toBe(true);
});
it('finds elements with `findByText`', () => {
expect(wrapper.findByText('GitLab frontend stack').exists()).toBe(true);
expect(wrapper.findByText('TypeScript').exists()).toBe(false);
});
2021-02-22 17:27:13 +05:30
2021-04-29 21:17:54 +05:30
it('finds elements with `findAllByRole`', () => {
expect(wrapper.findAllByRole('tab').length).toBe(3);
2021-02-22 17:27:13 +05:30
});
});
```
Check an example in [`spec/frontend/alert_management/components/alert_details_spec.js`](https://gitlab.com/gitlab-org/gitlab/-/blob/ac1c9fa4c5b3b45f9566147b1c88fd1339cd7c25/spec/frontend/alert_management/components/alert_details_spec.js#L32).
2019-12-04 20:38:33 +05:30
## Testing with older browsers
2020-06-23 00:09:42 +05:30
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:
2019-12-04 20:38:33 +05:30
2020-06-23 00:09:42 +05:30
### BrowserStack
2019-12-04 20:38:33 +05:30
2020-06-23 00:09:42 +05:30
[BrowserStack](https://www.browserstack.com/) allows you to test more than 1200 mobile devices and browsers.
2019-12-04 20:38:33 +05:30
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.
2021-02-22 17:27:13 +05:30
Sign in to BrowserStack with the credentials saved in the **Engineering** vault of the GitLab
2020-07-28 23:09:34 +05:30
[shared 1Password account](https://about.gitlab.com/handbook/security/#1password-guide).
2019-12-04 20:38:33 +05:30
### 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.
2021-02-22 17:27:13 +05:30
1. Select your preferred language. The DMG package is inside. Download it.
2019-12-04 20:38:33 +05:30
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.
2021-04-17 20:07:23 +05:30
## Snapshots
2021-04-29 21:17:54 +05:30
By now you've probably heard of [Jest snapshot tests](https://jestjs.io/docs/snapshot-testing) and why they are useful for various reasons.
2021-04-17 20:07:23 +05:30
To use them within GitLab, there are a few guidelines that should be highlighted:
- Treat snapshots as code
2023-03-04 22:38:38 +05:30
- Don't think of a snapshot file as a black box
2021-04-17 20:07:23 +05:30
- Care for the output of the snapshot, otherwise, it's not providing any real value. This will usually involve reading the generated snapshot file as you would read any other piece of code
Think of a snapshot test as a simple way to store a raw `String` representation of what you've put into the item being tested. This can be used to evaluate changes in a component, a store, a complex piece of generated output, etc. You can see more in the list below for some recommended `Do's and Don'ts`.
While snapshot tests can be a very powerful tool. They are meant to supplement, not to replace unit tests.
2021-04-29 21:17:54 +05:30
Jest provides a great set of docs on [best practices](https://jestjs.io/docs/snapshot-testing#best-practices) that we should keep in mind when creating snapshots.
2021-04-17 20:07:23 +05:30
### How does a snapshot work?
2023-03-04 22:38:38 +05:30
A snapshot is purely a stringified version of what you ask to be tested on the left-hand side of the function call. This means any kind of changes you make to the formatting of the string has an impact on the outcome. This process is done by leveraging serializers for an automatic transform step. For Vue this is already taken care of by leveraging the `vue-jest` package, which offers the proper serializer.
2021-04-17 20:07:23 +05:30
Should the outcome of your spec be different from what is in the generated snapshot file, you'll be notified about it by a failing test in your test suite.
2021-04-29 21:17:54 +05:30
Find all the details in Jests official documentation [https://jestjs.io/docs/snapshot-testing](https://jestjs.io/docs/snapshot-testing)
2021-04-17 20:07:23 +05:30
### How to take a snapshot
```javascript
it('makes the name look pretty', () => {
expect(prettifyName('Homer Simpson')).toMatchSnapshot()
})
```
When this test runs the first time a fresh `.snap` file will be created. It will look something like this:
```txt
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`makes the name look pretty`] = `
Sir Homer Simpson the Third
`
```
Now, every time you call this test, the new snapshot will be evaluated against the previously created version. This should highlight the fact that it's important to understand the content of your snapshot file and treat it with care. Snapshots will lose their value if the output of the snapshot is too big or complex to read, this means keeping snapshots isolated to human-readable items that can be either evaluated in a merge request review or are guaranteed to never change.
The same can be done for `wrappers` or `elements`
```javascript
it('renders the component correctly', () => {
expect(wrapper).toMatchSnapshot()
expect(wrapper.element).toMatchSnapshot();
})
```
2022-01-26 12:08:38 +05:30
The above test will create two snapshots. It's important to decide which of the snapshots provide more value for codebase safety. That is, if one of these snapshots changes, does that highlight a possible break in the codebase? This can help catch unexpected changes if something in an underlying dependency changes without our knowledge.
2021-04-17 20:07:23 +05:30
### Pros and Cons
**Pros**
- Speed up the creation of unit tests
- Easy to maintain
- Provides a good safety net to protect against accidental breakage of important HTML structures
**Cons**
- Is not a catch-all solution that replaces the work of integration or unit tests
- No meaningful assertions or expectations within snapshots
- When carelessly used with [GitLab UI](https://gitlab.com/gitlab-org/gitlab-ui) it can create fragility in tests when the underlying library changes the HTML of a component we are testing
A good guideline to follow: the more complex the component you may want to steer away from just snapshot testing. But that's not to say you can't still snapshot test and test your component as normal.
### When to use
**Use snapshots when**
- to capture a components rendered output
- to fully or partially match templates
- to match readable data structures
- to verify correctly composed native HTML elements
- as a safety net for critical structures so others don't break it by accident
- Template heavy component
- Not a lot of logic in the component
- Composed of native HTML elements
### When not to use
**Don't use snapshots when**
- To capture large data structures just to have something
- To just have some kind of test written
2021-06-08 01:23:25 +05:30
- To capture highly volatile UI elements without stubbing them (Think of GitLab UI version updates)
2021-04-17 20:07:23 +05:30
2023-01-13 00:05:48 +05:30
## Get started with feature tests
### What is a feature test
A [feature test](testing_levels.md#white-box-tests-at-the-system-level-formerly-known-as-system--feature-tests), also known as `white-box testing`, is a test that spawns a browser and has Capybara helpers. This means the test can:
- Locate an element in the browser.
- Click that element.
- Call the API.
Feature tests are expensive to run. You should make sure that you **really want** this type of test before running one.
All of our feature tests are written in `Ruby` but often end up being written by `JavaScript` engineers, as they implement the user-facing feature. So, the following section assumes no prior knowledge of `Ruby` or `Capybara`, and provide a clear guideline on when and how to use these tests.
### When to use feature tests
You should use a feature test when the test:
- Is across multiple components.
- Requires that a user navigate across pages.
- Is submitting a form and observing results elsewhere.
- Would result in a huge number of mocking and stubbing with fake data and components if done as a unit test.
Feature tests are especially useful when you want to test:
- That multiple components are working together successfully.
- Complex API interactions. Feature tests interact with the API, so they are slower but do not need any level of mocking or fixtures.
### When not to use feature tests
You should use `jest` and `vue-test-utils` unit tests instead of a feature test if you can get the same test results from these methods. Feature tests are quite expensive to run.
You should use a unit test if:
- The behavior you are implementing is all in one component.
- You can simulate other components' behavior to trigger the desired effect.
- You can already select UI elements in the virtual DOM to trigger the desired effects.
Also, if a behavior in your new code needs multiple components to work together, you should consider testing your behavior higher in the component tree. For example, let's say that we have a component called `ParentComponent` with the code:
```vue
<script>
export default{
name: ParentComponent,
data(){
return {
internalData: 'oldValue'
}
},
methods:{
changeSomeInternalData(newVal){
this.internalData = newVal
}
}
}
</script>
<template>
<div>
<child-component-1 @child-event="changeSomeInternalData" />
<child-component-2 :parent-data="internalData" />
</div>
</template>
```
In this example:
- `ChildComponent1` emits an event.
- `ParentComponent` changes its `internalData` value.
- `ParentComponent` passes the props down to `ChildComponent2`.
You can use a unit test instead by:
- From inside the `ParentComponent` unit test file, emitting the expected event from `childComponent1`
- Making sure the prop is passed down to `childComponent2`.
Then each child component unit tests what happens when the event is emitted and when the prop changes.
This example also applies at larger scale and with deeper component trees. It is definitely worth using unit tests and avoiding the extra cost of feature tests if you can:
- Confidently mount child components.
- Emit events or select elements in the virtual DOM.
- Get the test behavior that you want.
### Where to create your test
Feature tests live in `spec/features` folder. You should look for existing files that can test the page you are adding a feature to. Within that folder, you can locate your section. For example, if you wanted to add a new feature test for the pipeline page, you would look in `spec/features/projects/pipelines` and see if the test you want to write exists here.
### How to run a feature test
1. Make sure that you have a working GDK environment.
1. Start your `gdk` environment with `gdk start` command.
1. In your terminal, run:
```shell
bundle exec rspec path/to/file:line_of_my_test
```
You can also prefix this command with `WEBDRIVER_HEADLESS=0` which will run the test by opening an actual browser on your computer that you can see, which is very useful for debugging.
### How to write a test
#### Basic file structure
1. Make all string literals unchangeable
In all feature tests, the very first line should be:
```ruby
# frozen_string_literal: true
```
This is in every `Ruby` file and makes all string literals unchangeable. There are also some performance benefits, but this is beyond the scope of this section.
1. Import dependencies.
You should import the modules you need. You will most likely always need to require `spec_helper`:
```ruby
require 'spec_helper'
```
2023-03-17 16:20:25 +05:30
2023-01-13 00:05:48 +05:30
Import any other relevant module.
1. Create a global scope for RSpec to define our tests, just like what we do in jest with the initial describe block.
Then, you need to create the very first `RSpec` scope.
```ruby
RSpec.describe 'Pipeline', :js do
...
end
```
What is different though, is that just like everything in Ruby, this is actually a `class`. Which means that right at the top, you can `include` modules that you'd need for your test. For example, you could include the `RoutesHelpers` to navigate more easily.
```ruby
RSpec.describe 'Pipeline', :js do
include RoutesHelpers
...
end
```
After all of this implementation, we have a file that looks something like this:
```ruby
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Pipeline', :js do
include RoutesHelpers
end
```
#### Seeding data
Each test is in its own environment and so you must use a factory to seed the required data. To continue on with the pipeline example, let's say that you want a test that takes you to the main pipeline page, which is at the route `/namespace/project/-/pipelines/:id/`.
Most feature tests at least require you to create a user, because you want to be signed in. You can skip this step if you don't have to be signed in, but as a general rule, you should **always create a user unless you are specifically testing a feature looked at by an anonymous user**. This makes sure that you explicitly set a level of permission that you can edit in the test as needed to change or test a new level of permission as the section changes. To create a user:
```ruby
let(:user) { create(:user) }
```
This creates a variable that holds the newly created user and we can use `create` because we imported the `spec_helper`.
2023-03-17 16:20:25 +05:30
However, we have not done anything with this user yet because it's just a variable. So, in the `before do` block of the spec, we could sign in with the user so that every spec starts with an authenticated user.
2023-01-13 00:05:48 +05:30
```ruby
let(:user) { create(:user) }
before do
sign_in(user)
end
```
Now that we have a user, we should look at what else we'd need before asserting anything on a pipeline page. If you look at the route `/namespace/project/-/pipelines/:id/` we can determine we need a project and a pipeline.
So we'd create a project and pipeline, and link them together. Usually in factories, the child element requires its parent as an argument. In this case, a pipeline is a child of a project. So we can create the project first, and then when we create the pipeline, we are pass the project as an argument which "binds" the pipeline to the project. A pipeline is also owned by a user, so we need the user as well. For example, this creates a project and a pipeline:
```ruby
let(:user) { create(:user) }
let(:project) { create(:project, :repository) }
let(:pipeline) { create(:ci_pipeline, project: project, ref: 'master', sha: project.commit.id, user: user) }
```
In the same spirit, you could then create a job (build) by using the build factory and passing the parent pipeline:
```ruby
create(:ci_build, pipeline: pipeline, stage_idx: 10, stage: 'publish', name: 'CentOS')
```
There are many factories that already exists, so make sure to look at other existing files to see if what you need is available.
#### Navigation
You can navigate to a page by using the `visit` method and passing the path as an argument. Rails automatically generates helper paths, so make sure to use these instead of a hardcoded string. They are generated using the route model, so if we want to go to a pipeline, we'd use:
```ruby
visit project_pipeline_path(project, pipeline)
```
Before executing any page interaction when navigating or making asynchronous call through the UI, make sure to use `wait_for_requests` before proceeding with further instructions.
#### Elements interaction
2023-03-04 22:38:38 +05:30
There are a lot of different ways to find and interact with elements.
For best practises, refer to the [UI testing](best_practices.md#ui-testing) section.
2023-01-13 00:05:48 +05:30
2023-03-04 22:38:38 +05:30
To click a button, use `click_button` with the string of text found in the button:
2023-01-13 00:05:48 +05:30
```ruby
click_button 'Text inside the button element'
```
If you want to follow a link, then there is `click_link`:
```ruby
click_link 'Text inside the link tag'
```
You can use `fill_in` to fill input / form elements. The first argument is the selector, the second is `with:` which is the value to pass in.
```ruby
fill_in 'current_password', with: '123devops'
```
Alternatively, you can use the `find` selector paired with `send_keys` to add keys in a field without removing previous text, or `set` which completely replaces the value of the input element.
2023-03-04 22:38:38 +05:30
You can find a more comprehensive list of actions in the [feature tests actions](best_practices.md#actions) documentation.
2023-01-13 00:05:48 +05:30
#### Assertions
To assert anything in a page, you can always access `page` variable, which is automatically defines and actually means the page document. This means you can expect the `page` to have certain components like selectors or content. Here are a few examples:
```ruby
2023-03-04 22:38:38 +05:30
# Finding a button
expect(page).to have_button('Submit review')
2023-01-13 00:05:48 +05:30
```
```ruby
# Finding by text
2023-03-04 22:38:38 +05:30
expect(page).to have_text('build')
2023-01-13 00:05:48 +05:30
```
```ruby
# Finding by `href` value
expect(page).to have_link(pipeline.ref)
```
```ruby
2023-03-04 22:38:38 +05:30
# Find by data-testid
# Like CSS selector, this is acceptable when there isn't a specific matcher available.
expect(page).to have_css('[data-testid="pipeline-multi-actions-dropdown"]')
2023-01-13 00:05:48 +05:30
```
```ruby
2023-03-04 22:38:38 +05:30
# Finding by CSS selector. This is a last resort.
# For example, when you cannot add attributes on the desired element.
expect(page).to have_css('.js-icon-retry')
2023-01-13 00:05:48 +05:30
```
```ruby
# You can combine any of these selectors with `not_to` instead
2023-03-04 22:38:38 +05:30
expect(page).not_to have_button('Submit review')
2023-01-13 00:05:48 +05:30
```
```ruby
# When a test case has back to back expectations,
# it is recommended to group them using `:aggregate_failures`
it 'shows the issue description and design references', :aggregate_failures do
expect(page).to have_text('The designs I mentioned')
expect(page).to have_link(design_tab_ref)
expect(page).to have_link(design_ref_a)
expect(page).to have_link(design_ref_b)
end
```
You can also create a sub-block to look into, to:
- Scope down where you are making your assertions and reduce the risk of finding another element that was not intended.
- Make sure an element is found within the right boundaries.
```ruby
2023-03-04 22:38:38 +05:30
page.within('[data-testid="pipeline-multi-actions-dropdown"]') do
2023-01-13 00:05:48 +05:30
...
end
```
2023-03-04 22:38:38 +05:30
You can find a more comprehensive list of matchers in the [feature tests matchers](best_practices.md#matchers) documentation.
2023-01-13 00:05:48 +05:30
#### Feature flags
By default, every feature flag is enabled **regardless of the YAML definition or the flags you've set manually in your GDK**. To test when a feature flag is disabled, you must manually stub the flag, ideally in a `before do` block.
```ruby
stub_feature_flags(my_feature_flag: false)
```
If you are stubbing an `ee` feature flag, then use:
```ruby
stub_licensed_features(my_feature_flag: false)
```
### Debugging
You can run your spec with the prefix `WEBDRIVER_HEADLESS=0` to open an actual browser. However, the specs goes though the commands quickly and leaves you no time to look around.
To avoid this problem, you can write `binding.pry` on the line where you want Capybara to stop execution. You are then inside the browser with normal usage. To understand why you cannot find certain elements, you can:
- Select elements.
- Use the console and network tab.
- Execute selectors inside the browser console.
Inside the terminal, where capybara is running, you can also execute `next` which goes line by line through the test. This way you can check every single interaction one by one to see what might be causing an issue.
### Updating ChromeDriver
On MacOS, if you get a ChromeDriver error, make sure to update it by running
```shell
brew upgrade chromedriver
```
2018-03-17 18:26:18 +05:30
---
[Return to Testing documentation](index.md)