|
| 1 | +# Stubbing Services in Tests |
| 2 | + |
| 3 | +We have a problem: our tests only pass, when we're logged in with a particular userId -- because they're actually reading/writing to cookies! This is a leak, and we need to fix it |
| 4 | + |
| 5 | +Create a file in your tests folder like [`tests/test-helpers/auth-service.js`](../tests/test-helpers/auth-service.js), where we'll put our "stub" service that will be used in place of the real one during tests |
| 6 | + |
| 7 | +```js |
| 8 | +import Service, { inject as service } from '@ember/service'; |
| 9 | +import Router from '@ember/routing/router'; |
| 10 | +import { tracked } from '@glimmer/tracking'; |
| 11 | + |
| 12 | +export default class StubbedAuthService extends Service { |
| 13 | + /** |
| 14 | + * @type {Router} |
| 15 | + */ |
| 16 | + @service router; |
| 17 | + /** |
| 18 | + * @type {string} |
| 19 | + */ |
| 20 | + @tracked currentUserId = null; |
| 21 | + |
| 22 | + get isAuthenticated() { |
| 23 | + return !!this.currentUserId; |
| 24 | + } |
| 25 | + |
| 26 | + loginWithUserId(id) { |
| 27 | + this.currentUserId = id; |
| 28 | + this.router.transitionTo('teams'); |
| 29 | + } |
| 30 | +} |
| 31 | +``` |
| 32 | + |
| 33 | +Now we just need to install it. Go to [`tests/integration/components/team-sidebar-test.js`](../tests/integration/components/team-sidebar-test.js) and begin by importing the stub service |
| 34 | + |
| 35 | +```js |
| 36 | +import StubbedAuthService from 'shlack/tests/test-helpers/auth-service'; |
| 37 | +``` |
| 38 | + |
| 39 | +Now we just need to "register" the service before each test, ensuring our test-appropriate one is used in place of the real one. Put this code in the test module, but before any tests. |
| 40 | + |
| 41 | +```js |
| 42 | +hooks.beforeEach(function() { |
| 43 | + this.owner.register('service:auth', StubbedAuthService); |
| 44 | +}); |
| 45 | +``` |
| 46 | + |
| 47 | +Finally, at the beginning of the test, set the state of the service according to our needs |
| 48 | + |
| 49 | +```js |
| 50 | +this.owner.lookup('service:auth').currentUserId = 'LOL'; |
| 51 | +``` |
| 52 | + |
| 53 | +Make an appropriate adjustment to the assertion value, taking the userId into account and you should be good to go! |
0 commit comments