It may be some variation.
function setupUserTestbed() { beforeEach(() => { TestBed.configureTestingModule({...}); }); afterEach(() => { TestBed.resetTestingModule(); }); } ... setupUserTestbed(); ... setupUserTestbed();
But the purpose of the describe blocks (in addition to grouping the specifications in the test report) is to arrange the before* and after* blocks so that they are the most efficient.
If the top-level describe block has a beforeEach block, you can be sure that it affects the specifications in the nested describe blocks. If the describe blocks are siblings, the general behavior should be moved to the upper level describe . If there is no top level describe for sibling describe blocks, it must be created.
The published top-level code describe('User service - ', () => { ... }) already has beforeEach blocks with TestBed.configureTestingModule , TestBed.resetTestingModule (this should be done in afterEach ) and inject . There is no need to duplicate them in nested describe blocks.
The recipe for the MockRestService class is the same as for any layout that alternates between specifications. This should be a let / var variable:
describe(... let MockRestService = class MockRestService { ... }; beforeEach(() => { Testbed... }); describe(... MockRestService = class MockRestService { ... }; beforeEach(inject(...));
There may be many variations of this pattern. The class itself may be constant, but the getUser and upsertUser may alternate:
let getUserSpy; let upsertUserSpy; class MockRestService { getUser = getUserSpy; ... } describe(... beforeEach(() => { Testbed... }); beforeEach(() => { getUserSpy = jasmine.createSpy().and.returnValue(...); ... }); describe(... beforeEach(() => { getUserSpy = jasmine.createSpy().and.returnValue(...); ... }); beforeEach(inject(...));
This also solves an important problem, because spies must be fresh in every specification, i.e. be defined in beforeEach . getUserSpy and upsertUserSpy can be reassigned after the Testbed configuration, but before inject (an instance of the MockRestService class can be created MockRestService ).