Skip to content

Commit

Permalink
Add handling for invalid tokens
Browse files Browse the repository at this point in the history
Thanks to @ppcano for the visitWithAbortedTransition suggestion here:
emberjs/ember-test-helpers#332
  • Loading branch information
backspace committed Nov 25, 2019
1 parent 86ce123 commit dbd7adb
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 1 deletion.
14 changes: 13 additions & 1 deletion app/routes/team.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,18 @@ export default class TeamRoute extends Route {
Authorization: `Bearer ${this.get('tokenStorage.token')}`,
}),
method: 'POST',
}).then(response => response.json());
})
.then(response => {
if (response.ok) {
return response.json();
} else {
throw new Error();
}
})
.catch(() => {
this.tokenStorage.reset();
this.controllerFor('application').set('error', 'Invalid token');
this.transitionTo('application');
});
}
}
3 changes: 3 additions & 0 deletions app/templates/application.hbs
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,9 @@

{{outlet}}
{{else}}
{{#if this.error}}
<p data-test-error>{{this.error}}</p>
{{/if}}
<label for="token-input">Token</label>
<Input @id="token-input" @value={{this.tokenFieldValue}} data-test-token-field />

Expand Down
27 changes: 27 additions & 0 deletions tests/acceptance/require-setup-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { module, test } from 'qunit';
import { click, fillIn, visit } from '@ember/test-helpers';
import { setupApplicationTest } from 'ember-qunit';
import { setupMirage } from 'ember-cli-mirage/test-support';
import { Response } from 'ember-cli-mirage';
import resetStorages from 'ember-local-storage/test-support/reset-storage';

module('Acceptance | require setup', function(hooks) {
Expand Down Expand Up @@ -33,4 +34,30 @@ module('Acceptance | require setup', function(hooks) {
assert.dom('.text-2xl').exists();
assert.dom('[data-test-team-name]').hasText('our team');
});

test('it returns to the token field when auth fails', async function(assert) {
const applicationController = this.owner.lookup('controller:application');
applicationController.set('tokenStorage.token', 1);

this.server.post('/auth', () => {
return new Response(401, {}, {});
});

await visitWithAbortedTransition('/team');

assert.dom('.text-2xl').doesNotExist();
assert.dom('[data-test-token-field]').exists();
assert.dom('[data-test-error]').hasText('Invalid token');
});
});

async function visitWithAbortedTransition(url) {
try {
await visit(url);
} catch (error) {
const { message } = error;
if (message !== 'TransitionAborted') {
throw error;
}
}
}

0 comments on commit dbd7adb

Please sign in to comment.