I recently started utilizing ng-mocks to streamline my testing process. However, I am struggling to figure out how to modify the value of mock providers in nested describes/tests after MockBuilder/MockRender have already been defined.
Specifically, my question is: Is it possible to change the value of mock providers in nested describes/tests post MockBuilder/MockRender setup?
In my application, I often encounter scenarios where components depend on services that offer different data based on the context. Testing this when the data is static is straightforward. Let's take ActivatedRoute as an example:
const mockActivatedRoute = { snapshot: { params: { id: 1 } };
describe('MyComponent', () => {
MockInstance.scope('all');
beforeEach(() => {
return MockBuilder(MyComponent, MyModule)
.provide({ provide: ActivatedRoute, useValue: mockActivatedRoute })
});
beforeEach(() => {
fixture = MockRender(MyComponent);
component = fixture.point.componentInstance;
});
// Assume the component has a routeId provided by the ActivatedRoute
it('should have an id of 1', () => { expect(component.routeId).toEqual(1); });
});
So far so good.
However, following this test, I want to run another suite that alters the service; perhaps now the id
should be changed to 2. I assumed that MockInstance
would allow me to modify the provided services dynamically for individual tests.
To extend on my example, I will include a nested describe
within the initial one after the first test:
describe('MyComponent', () => {
...
describe('when initialized with a different id', () => {
MockInstance.scope();
beforeEach(MockInstance(mockActivatedRoute, () => {
snapshot: { params: { id: 2 } }
}));
it('should have an id of 2', () => { expect(component.routeId).toEqual(2); });
});
});
This test fails because the new mock value was not applied, and the routeId
remained unchanged.
While I understand this example may not be ideal, I have attempted various approaches like using MockInstance.remember
or attempting to initialize the service instance itself without success. It seems that MockBuilder and MockInstance might not be intended to be used together, as there are no documented examples on the ng-mocks website. It appears that creating separate describes
with their own MockBuilder and MockRender may be the only way to handle such scenarios.
Alternatively, would it be best to make routeId
public and directly manipulate it?