Reputation: 111
I'm setting up some Angular Component Unit Tests using Cypress. In one of my tests, as part of the arrange phase of the test, I want to either override a property of the component or override a property of a Service that I'm providing. This is the relevant part of the component in question:
export class ToolbarComponent {
constructor(private accountService: AccountService) { }
loggedOnUser$ = this.accountService.loggedOnUser$;
The component is mounted within a beforeEach()
in my test:
const accountService = getMockAccountService();
beforeEach(() => {
cy.mount(ToolbarComponent, setupCypressConfig<ToolbarComponent>({
autoSpyOutputs: true,
providers: [{
provide: AccountService,
useValue: accountService
}]
}));
});
This is the test where I would like to override the loggedOnUser$
in either the accountService
or the component itself:
describe('login button', () => {
it('should be visible when user is not logged in', () => {
cy.stub(accountService, 'loggedOnUser$').value(of(null)); // THIS VALUE IS NOT UPDATING
cy.wait(1000);
cy.get(elementBindings.loginButton).should('be.visible');
});
});
Is it possible to update the properties in either the accountService
or the component itself, once the component has already been mounted?
I could of course re mount the component:
describe('login button', () => {
it('should be visible when user is not logged in', () => {
cy.mount(ToolbarComponent, setupCypressConfig<ToolbarComponent>({
providers: [{
provide: AccountService,
useValue: {loggedOnUser$: of(null)}
}]
}));
cy.wait(1000);
cy.get(elementBindings.loginButton).should('be.visible');
});
});
The test passes when I re mount it but I was hoping that Cypress had an API which would allow me to simply override the property instead? Couldn't find anything in the docs which makes me think this is possible.
Does anyone have any ideas?
Upvotes: -1
Views: 750
Reputation: 55
Your providers array already mock the AccountService
to local instance accountService
.
I would expect the property of the local can be altered directly.
//cy.stub(accountService, 'loggedOnUser$').value(of(null))
accountService.loggedOnUser$ = of(null)
It works for a property returning a number, haven't tested with an observable value but see no reason why not if your re-mount example is working.
The only problem is the static assignment within ToolbarComponent. The value has already been accessed on instantiation. If there's a way to reset it with a method call, the test can do so without remounting.
Upvotes: 5