- 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-foss/issues/58205).
- 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.
- Jest does not have access to Webpack loaders or aliases.
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).
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.
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.
- Files in `spec/frontend/mocks/node` will mock NPM packages of the same name or path.
- We don't support mocking EE modules yet.
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.
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.
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.
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.
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 >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.
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:
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/`.
-`spec/features/` which are run by RSpec and contain
- [feature tests](#feature-tests)
All tests in `spec/javascripts/` will eventually be migrated to `spec/frontend/` (see also [#52483](https://gitlab.com/gitlab-org/gitlab-foss/issues/52483)).
In addition, there used to be feature tests in `features/`, run by Spinach.
These were removed from the codebase in May 2018 ([#23036](https://gitlab.com/gitlab-org/gitlab-foss/issues/23036)).
See also [Notes on testing Vue components](../fe_guide/vue.html#testing-vue-components).
### Frontend unit tests
Unit tests are on the lowest abstraction level and typically test functionality that is not directly perceivable by a user.
Background operations cannot be stopped or waited on, so they will continue running in the following tests and cause side effects.
</details>
#### What *not* to mock in unit tests
<details>
<summary>non-exported functions or classes</summary>
Everything that is not exported can be considered private to the module and will be implicitly tested via the exported classes / functions.
</details>
<details>
<summary>methods of the class under test</summary>
By mocking methods of the class under test, the mocks will be tested and not the real methods.
</details>
<details>
<summary>utility functions (pure functions, or those that only modify parameters)</summary>
If a function has no side effects because it has no state, it is safe to not mock it in tests.
</details>
<details>
<summary>full HTML pages</summary>
Loading the HTML of a full page slows down tests, so it should be avoided in unit tests.
</details>
### Frontend component tests
Component tests cover the state of a single component that is perceivable by a user depending on external signals such as user input, events fired from other components, or application state.
Similar to unit tests, background operations cannot be stopped or waited on, so they will continue running in the following tests and cause side effects.
</details>
<details>
<summary>child components</summary>
Every component is tested individually, so child components are mocked.
See also <ahref="https://vue-test-utils.vuejs.org/api/#shallowmount">shallowMount()</a>
</details>
#### What *not* to mock in component tests
<details>
<summary>methods or computed properties of the component under test</summary>
By mocking part of the component under test, the mocks will be tested and not the real component.
</details>
<details>
<summary>functions and classes independent from Vue</summary>
All plain JavaScript code is already covered by unit tests and needs not to be mocked in component tests.
</details>
### Frontend integration tests
Integration tests cover the interaction between all components on a single page.
Their abstraction level is comparable to how a user would interact with the UI.
Rendering HAML views requires a Rails environment including a running database which we cannot rely on in frontend tests.
</details>
<details>
<summary>all server requests</summary>
Similar to unit and component tests, when running component tests, the backend may not be reachable.
Therefore all outgoing requests need to be mocked.
</details>
<details>
<summary>asynchronous background operations that are not perceivable on the page</summary>
Background operations that affect the page need to be tested on this level.
All other background operations cannot be stopped or waited on, so they will continue running in the following tests and cause side effects.
</details>
#### What *not* to mock in integration tests
<details>
<summary>DOM</summary>
Testing on the real DOM ensures our components work in the environment they are meant for.
Part of this will be delegated to <ahref="https://gitlab.com/gitlab-org/quality/team-tasks/issues/45">cross-browser testing</a>.
</details>
<details>
<summary>properties or state of components</summary>
On this level, all tests can only perform actions a user would do.
For example to change the state of a component, a click event would be fired.
</details>
<details>
<summary>Vuex stores</summary>
When testing the frontend code of a page as a whole, the interaction between Vue components and Vuex stores is covered as well.
</details>
### Feature tests
In contrast to [frontend integration tests](#frontend-integration-tests), feature tests make requests against the real backend instead of using fixtures.
This also implies that database queries are executed which makes this category significantly slower.
See also the [RSpec testing guidelines](../testing_guide/best_practices.md#rspec).
- Use cases that require a backend and cannot be tested using fixtures.
- Behavior that is not part of a page bundle but defined globally.
#### Relevant notes
A `:js` flag is added to the test to make sure the full environment is loaded.
```ruby
scenario 'successfully', :js do
sign_in(create(:admin))
end
```
The steps of each test are written using capybara methods ([documentation](https://www.rubydoc.info/gems/capybara)).
Bear in mind <abbrtitle="XMLHttpRequest">XHR</abbr> calls might require you to use `wait_for_requests` in between steps, like so:
```ruby
find('.form-control').native.send_keys(:enter)
wait_for_requests
expect(page).not_to have_selector('.card')
```
## 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):
```javascript
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,
);
```
Check an example in [spec/javascripts/ide/stores/actions_spec.jsspec/javascripts/ide/stores/actions_spec.js](https://gitlab.com/gitlab-org/gitlab-foss/blob/master/spec/javascripts/ide/stores/actions_spec.js).
### 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:
```javascript
beforeEach(() => {
vm = createComponentWithStore(Component, store);
vm.$store.state.currentBranchId = 'master';
vm.$mount();
});
```
```javascript
beforeEach(() => {
vm = mountComponentWithStore(Component, {
el: '#dummy-element',
store,
props: { badge },
});
});
```
Don't forget to clean up:
```javascript
afterEach(() => {
vm.$destroy();
});
```
### 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.
## 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.