Skip to content

Commit

Permalink
[TECH] Utilisation des session et currentUser service stubs dans Pix …
Browse files Browse the repository at this point in the history
…App (PIX-15677)

 #10776
  • Loading branch information
pix-service-auto-merge authored Dec 13, 2024
2 parents e67fa40 + 41b71f4 commit 105d747
Show file tree
Hide file tree
Showing 34 changed files with 355 additions and 641 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import isEmpty from 'lodash/isEmpty';
import ENV from 'mon-pix/config/environment';

export default class DataProtectionPolicyInformationBanner extends Component {
@service session;
@service currentUser;
@service currentDomain;
@service intl;
Expand All @@ -14,8 +15,7 @@ export default class DataProtectionPolicyInformationBanner extends Component {
_rawBannerContent = ENV.APP.BANNER_CONTENT;

get shouldDisplayDataProtectionPolicyInformation() {
const isUserLoggedIn = typeof this.currentUser.user !== 'undefined';
if (!isUserLoggedIn) {
if (!this.session.isAuthenticated) {
return false;
}

Expand Down
93 changes: 75 additions & 18 deletions mon-pix/tests/helpers/service-stubs.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import Service from '@ember/service';
import omit from 'lodash/omit';
import sinon from 'sinon';

/**
Expand All @@ -11,18 +12,17 @@ import sinon from 'sinon';
* @param {string} [sessionData.externalUserTokenFromGar='external-user-token'] - The external user token from GAR.
* @param {string} [sessionData.userIdForLearnerAssociation='expected-user-id'] - The expected user ID from GAR.
* @param {string} [sessionData.source='pix'] - The source of authentication.
* @param {string} [sessionData.userId] - The user ID.
* @returns {Service} The stubbed session service.
*/
export function stubSessionService(owner, sessionData = {}) {
const isAuthenticated = sessionData.isAuthenticated || false;
const isAuthenticatedByGar = sessionData.isAuthenticatedByGar || false;
const externalUserTokenFromGar = sessionData.externalUserTokenFromGar || 'external-user-token';
const userIdForLearnerAssociation = sessionData.userIdForLearnerAssociation;
const userId = isAuthenticated ? sessionData.userId || 123 : null;
const source = isAuthenticated ? sessionData.source || 'pix' : null;

/**
* Stub class for the session service.
*/
class SessionStub extends Service {
constructor() {
super();
Expand All @@ -31,7 +31,9 @@ export function stubSessionService(owner, sessionData = {}) {
this.userIdForLearnerAssociation = userIdForLearnerAssociation;

if (isAuthenticated) {
this.data = { authenticated: { source } };
this.data = {
authenticated: { user_id: userId, source, access_token: 'access_token!', scope: 'mon-pix' },
};
} else {
this.data = {};
}
Expand All @@ -51,6 +53,7 @@ export function stubSessionService(owner, sessionData = {}) {
}
}

owner.unregister('service:session');
owner.register('service:session', SessionStub);
return owner.lookup('service:session');
}
Expand All @@ -63,41 +66,95 @@ export function stubSessionService(owner, sessionData = {}) {
* @param {boolean} [userData.isAnonymous=false] - Indicates if the user is anonymous.
* @param {string} [userData.firstName='John'] - The first name of the user.
* @param {string} [userData.lastName='Doe'] - The last name of the user.
* @param {string} [userData.email] - The email of the user.
* @param {Object} [userData.profile] - The profile of the user.
* @param {boolean} [userData.mustValidateTermsOfService=false] - Indicates if the user must validate terms of service.
* @param {boolean} [userData.hasRecommendedTrainings=false] - Indicates if the user has recommended trainings.
* @param {boolean} [userData.hasAssessmentParticipations=false] - Indicates if the user has assessment participations.
* @param {boolean} [userData.hasSeenOtherChallengesTooltip=false] - Indicates if the user has seen the other challenges tooltip.
* @param {boolean} [userData.hasSeenFocusedChallengeTooltip=false] - Indicates if the user has seen the focused challenge tooltip.
* @param {boolean} [userData.shouldSeeDataProtectionPolicyInformationBanner=false] - Indicates if the user should see the data protection policy information banner.
* @param {string} [userData.codeForLastProfileToShare] - The code for the last profile to share.
* @param {boolean} [withStoreStubbed=true] - Indicates to stub the store.
* @returns {Service} The stubbed current user service.
*/
export function stubCurrentUserService(owner, userData = {}) {
export function stubCurrentUserService(owner, userData = {}, { withStoreStubbed } = { withStoreStubbed: true }) {
const isAuthenticated = userData.isAuthenticated ?? true;
const isAnonymous = userData.isAnonymous || false;
const id = userData.id || 123;
const firstName = userData.firstName || 'John';
const lastName = userData.lastName || 'Doe';
const fullName = `${firstName} ${lastName}`;
const email = userData.email || `${firstName.toLowerCase()}.${lastName.toLowerCase()}@example.net`;
const codeForLastProfileToShare = userData.codeForLastProfileToShare || null;
const mustValidateTermsOfService = userData.mustValidateTermsOfService || false;
const hasRecommendedTrainings = userData.hasRecommendedTrainings || false;
const hasAssessmentParticipations = userData.hasAssessmentParticipations || false;
const hasSeenOtherChallengesTooltip = userData.hasSeenOtherChallengesTooltip || false;
const hasSeenFocusedChallengeTooltip = userData.hasSeenFocusedChallengeTooltip || false;
const shouldSeeDataProtectionPolicyInformationBanner =
userData.shouldSeeDataProtectionPolicyInformationBanner || false;

const profile = userData.profile
? createRecord({ owner, key: 'profile', data: userData.profile, withStoreStubbed })
: null;

/**
* Stub class for the current user service.
*/
class CurrentUserStub extends Service {
constructor() {
super();
if (isAnonymous) {
this.user = { isAnonymous: true };

if (!isAuthenticated) {
this.user = null;
} else if (isAnonymous) {
this.user = createRecord({
owner,
key: 'user',
data: { id, isAnonymous: true },
withStoreStubbed,
});
} else {
this.user = {
isAnonymous: false,
firstName,
lastName,
fullName,
hasRecommendedTrainings,
mustValidateTermsOfService,
};
this.user = createRecord({
owner,
key: 'user',
data: {
isAnonymous: false,
id,
email,
firstName,
lastName,
fullName,
profile,
codeForLastProfileToShare,
mustValidateTermsOfService,
hasRecommendedTrainings,
hasSeenFocusedChallengeTooltip,
hasSeenOtherChallengesTooltip,
hasAssessmentParticipations,
shouldSeeDataProtectionPolicyInformationBanner,
},
withStoreStubbed,
});
}

this.load = sinon.stub();
}
}

owner.unregister('service:current-user');
owner.register('service:current-user', CurrentUserStub);
return owner.lookup('service:current-user');
}

function createRecord({ owner, key, data, withStoreStubbed }) {
if (withStoreStubbed) {
return {
...data,
save: sinon.stub(),
get: sinon.stub(),
set: sinon.stub(),
};
}

const store = owner.lookup('service:store');
return store.createRecord(key, omit(data, ['fullName']));
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import LoginForm from 'mon-pix/components/authentication/login-form';
import { module, test } from 'qunit';
import sinon from 'sinon';

import { stubSessionService } from '../../../helpers/service-stubs';
import setupIntlRenderingTest from '../../../helpers/setup-intl-rendering';

const I18N_KEYS = {
Expand All @@ -26,8 +27,7 @@ module('Integration | Component | Authentication | LoginForm', function (hooks)
hooks.beforeEach(async function () {
storeService = this.owner.lookup('service:store');
routerService = this.owner.lookup('service:router');
sessionService = this.owner.lookup('service:session');
sinon.stub(sessionService, 'authenticateUser');
sessionService = stubSessionService(this.owner, { isAuthenticated: false });

screen = await render(<template><LoginForm /></template>);
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import SignupForm from 'mon-pix/components/authentication/signup-form';
import { module, test } from 'qunit';
import sinon from 'sinon';

import { stubSessionService } from '../../../../helpers/service-stubs';
import setupIntlRenderingTest from '../../../../helpers/setup-intl-rendering';

const I18N_KEYS = {
Expand All @@ -21,8 +22,7 @@ module('Integration | Component | Authentication | SignupForm | index', function
let sessionService;

hooks.beforeEach(async function () {
sessionService = this.owner.lookup('service:session');
sinon.stub(sessionService, 'authenticateUser');
sessionService = stubSessionService(this.owner, { isAuthenticated: false });
});

test('it signs up successfully', async function (assert) {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import { render } from '@1024pix/ember-testing-library';
import Service from '@ember/service';
import { click } from '@ember/test-helpers';
import { hbs } from 'ember-cli-htmlbars';
import { t } from 'ember-intl/test-support';
import { module, test } from 'qunit';
import sinon from 'sinon';

import { stubSessionService } from '../../../helpers/service-stubs.js';
import setupIntlRenderingTest from '../../../helpers/setup-intl-rendering';

module('Integration | Component | Autonomous Course | Landing page start block', function (hooks) {
Expand All @@ -28,7 +28,13 @@ module('Integration | Component | Autonomous Course | Landing page start block',
assert.dom(screen.getByText('dummy landing page text')).exists();
});

module('when user is anonymous', function () {
module('when user is anonymous', function (hooks) {
let sessionService;

hooks.beforeEach(function () {
sessionService = stubSessionService(this.owner, { isAuthenticated: false });
});

test('should display the launcher block', async function (assert) {
// when
const screen = await render(hbs`<AutonomousCourse::LandingPageStartBlock />`);
Expand Down Expand Up @@ -63,7 +69,6 @@ module('Integration | Component | Autonomous Course | Landing page start block',
});

test('should redirect to log-in form on specific button click', async function (assert) {
const sessionService = this.owner.lookup('service:session');
sessionService.requireAuthenticationAndApprovedTermsOfService = sinon.stub().resolves();

this.set('startCampaignParticipation', sinon.stub());
Expand All @@ -88,11 +93,7 @@ module('Integration | Component | Autonomous Course | Landing page start block',
module('when user is logged', function () {
test('should start campaign participation on main button click', async function (assert) {
// given
class SessionStub extends Service {
isAuthenticated = true;
}

this.owner.register('service:session', SessionStub);
stubSessionService(this.owner, { isAuthenticated: true });
this.set('startCampaignParticipation', sinon.stub());

// when
Expand Down
59 changes: 9 additions & 50 deletions mon-pix/tests/integration/components/campaign-start-block-test.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import { render } from '@1024pix/ember-testing-library';
import Service from '@ember/service';
import { click } from '@ember/test-helpers';
import { hbs } from 'ember-cli-htmlbars';
import { t } from 'ember-intl/test-support';
import { module, test } from 'qunit';
import sinon from 'sinon';

import { stubCurrentUserService, stubSessionService } from '../../helpers/service-stubs';
import setupIntlRenderingTest from '../../helpers/setup-intl-rendering';

module('Integration | Component | campaign-start-block', function (hooks) {
Expand Down Expand Up @@ -44,23 +44,9 @@ module('Integration | Component | campaign-start-block', function (hooks) {
let session;

hooks.beforeEach(function () {
class currentUser extends Service {
user = {
firstName: 'Izuku',
lastName: 'Midorya',
isAnonymous: false,
};
}

this.owner.register('service:currentUser', currentUser);

class SessionStub extends Service {
isAuthenticated = true;
invalidate = sinon.stub();
}

this.owner.register('service:session', SessionStub);
session = this.owner.lookup('service:session', SessionStub);
stubCurrentUserService(this.owner, { firstName: 'Izuku', lastName: 'Midorya' });
session = stubSessionService(this.owner, { isAuthenticated: true });

this.set('campaign', {});
this.set('startCampaignParticipation', sinon.stub());
});
Expand Down Expand Up @@ -187,22 +173,8 @@ module('Integration | Component | campaign-start-block', function (hooks) {

module('When the user is not authenticated', function (hooks) {
hooks.beforeEach(function () {
class currentUser extends Service {
user = {
firstName: 'Izuku',
lastName: 'Midorya',
isAnonymous: false,
};
}

this.owner.register('service:currentUser', currentUser);

class SessionStub extends Service {
isAuthenticated = false;
invalidate = sinon.stub();
}

this.owner.register('service:session', SessionStub);
stubCurrentUserService(this.owner, { firstName: 'Izuku', lastName: 'Midorya' });
stubSessionService(this.owner, { isAuthenticated: false });
this.set('campaign', {});
this.set('startCampaignParticipation', sinon.stub());
});
Expand Down Expand Up @@ -273,22 +245,9 @@ module('Integration | Component | campaign-start-block', function (hooks) {

module('When the user has isAnonymous', function (hooks) {
hooks.beforeEach(function () {
class currentUser extends Service {
user = {
firstName: 'Izuku',
lastName: 'Midorya',
isAnonymous: true,
};
}

this.owner.register('service:currentUser', currentUser);

class SessionStub extends Service {
isAuthenticated = true;
invalidate = sinon.stub();
}

this.owner.register('service:session', SessionStub);
stubCurrentUserService(this.owner, { isAnonymous: true });
stubSessionService(this.owner, { isAuthenticated: true });

this.set('campaign', {});
this.set('startCampaignParticipation', sinon.stub());
});
Expand Down
Loading

0 comments on commit 105d747

Please sign in to comment.