I've got an Angular test suite which uses a MockActivatedRoute class I created. All of the values are null except when I need to set them for a given test. In general it works great, but now I'm in a situation where I need two different values for the route.snapshot.data.session.permissions array: one test where the array can be empty and one where it needs a specific value.
I've tried:
- spying on the permissions array and using Jest's
returnValuemethod; jest.replaceProperty(route.snapshot.data.session, 'permissions, [Permissions.VIEW_REQUEST_SUMMARY_PERMISSION]);, including callingfixture.detectChanges();; and- creating an
ActivatedRoutedefinition inline, and usingTestbed.injectwithin the individual test;
but for some reason the permissions array never changes from what is set at the beginning of the test suite. Can someone help me figure out how to change this value?
- Angular: 18.2.13
- Jest: 29.7.0
The code being tested:
ngOnInit() {
const userSession = this.activatedRoute.snapshot.data.session;
if (userSession.permissions.includes(Permissions.VIEW_REQUEST_SUMMARY_PERMISSION)) {
this.getRequestSummary();
}
}
The test suite:
import { MockActivatedRoute } from 'src/app/mocks/mock.activated-route';
describe('SidebarComponent', () => {
let component: SidebarComponent;
let fixture: ComponentFixture<SidebarComponent>;
let route = new MockActivatedRoute();
route.snapshot = { data: { session: { permissions: []},},};
beforeEach(async () => {
TestBed.configureTestingModule({
imports: [],
providers:[
provideHttpClient(),
provideHttpClientTesting(),
{ provide: ActivatedRoute, useValue: route},
],
declarations: [ SidebarComponent ],
schemas: [NO_ERRORS_SCHEMA],
})
.compileComponents();
fixture = TestBed.createComponent(SidebarComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
// the following test passes
// I left out the definition of mockAccountsService in this example for brevity
it('should not call getRequestSummary when Permissions.VIEW_REQUEST_SUMMARY_PERMISSION does not exist', () => {
const spy = jest.spyOn(mockAccountsService, 'getRequests');
expect(spy).not.toHaveBeenCalled();
});
it('should call getRequestSummary when Permissions.VIEW_REQUEST_SUMMARY_PERMISSION does exist', () => {
// these are my attempts
const spyRoute = jest.spyOn(route.snapshot.data.session, 'permissions');
spyRoute.mockReturnValue([Permissions.VIEW_REQUEST_SUMMARY_PERMISSION]);
jest.replaceProperty(route.snapshot.data.session, 'permissions', [Permissions.VIEW_REQUEST_SUMMARY_PERMISSION]);
const spy = jest.spyOn(mockAccountsService, 'getRequests');
fixture.detectChanges();
expect(spy).toHaveBeenCalled();
});
});
MockActivatedRouteimplementation code ?