Acceptance test failing because of authentication


#1

Hi guys, I am writing the following acceptance test:

test('visiting /posts', function(assert) {
  visit('/posts');

  andThen(function() {
    assert.equal(currentURL(), '/posts');
  });
});

But it is failing because I haven’t logged in, so the application redirects me to login page. Here is what I get from QUnit:

Expected: 	
"/posts"
Result: 	
"/login"
Diff: 	
"/postslogin"

How do I make sure the testing environment is already logged in?

Side Note: I am not using ember-simple-auth for authentication, but a user service.


#2

Hey @Jeffrey_Cheung, it really depends on your authentication code, but you’ll need some sort of mechanism for notifying your authentication system that you’re (fake) authenticated or that you don’t need to be. You could stub some methods or values on the user service perhaps?

The best approach that I could recommend is probably to look at what ember-simple-auth does for inspiration. There is a test helper for fake authenticating in acceptance tests, and essentially all you have to do is import it and call it in “beforeEach” and it, for testing purposes, tells ESA that you’re authenticated.


#3

I end up stubbing a service into my acceptance test.

const userStub = Ember.Service.extend({
  email: 'test@testing.com',
  token: '',
  isLoggedIn() {
    return true;
  },
});

test('visiting /cameras with login', function(assert) {
  this.application.register('service:user-service', userStub);
  this.application.inject('route:application', 'currentUser', 'service:user-service');
  visit('/cameras');

  andThen(function() {
    assert.equal(currentURL(), '/cameras');
  });
});

It works. I also made a PR to ember guides to show how to do acceptance test service. Take a look here.