Given an Angular component that uses a mocked service returning of('Hello Mock'), what will the component render?
import { Component } from '@angular/core'; import { of } from 'rxjs'; class MockService { getData() { return of('Hello Mock'); } } @Component({ selector: 'app-test', template: `<p>{{ message }}</p>` }) export class TestComponent { message = ''; constructor(private service: MockService) { this.service.getData().subscribe(data => this.message = data); } }
Think about what the mocked service returns and how the component subscribes to it.
The mocked service returns an observable emitting 'Hello Mock'. The component subscribes and sets message to this value, so the template displays it.
In an Angular test, you want to mock a service method fetchData() that returns a Promise resolving to 42. Which mock implementation is correct?
Remember how to create a resolved Promise with a value.
Only Promise.resolve(42) creates a Promise that resolves to 42. The others are either syntax errors or create rejected Promises.
In an Angular test, the mocked service method getData() is expected to be called once, but the test fails saying it was never called. What is the most likely cause?
Check which service instance the component uses during the test.
If the component uses the real service instead of the mocked one, the mocked method is never called, causing the test to fail.
In an Angular component, a mocked service method is called inside ngOnInit(). When will this method be invoked during testing?
Recall when ngOnInit() runs in Angular.
ngOnInit() runs right after the component is created but before Angular runs change detection, so the mocked service method is called immediately after creation.
Why do Angular developers use mocked services instead of real services in unit tests?
Think about what unit tests aim to achieve regarding dependencies.
Mocked services isolate the component from real dependencies, allowing focused and reliable tests without side effects or network calls.