Angular Web Framework Testing & Debugging 2 — Questions and Answers
Question 1: Which Angular testing utility method is used to trigger change detection manually in a component test?
- fixture.detectChanges() (Correct answer)
- fixture.update()
- TestBed.refresh()
- component.ngOnChanges()
Correct answer: fixture.detectChanges()
fixture.detectChanges() triggers Angular's change detection cycle so the view reflects the component's current state.
Question 2: What is the purpose of the `NO_ERRORS_SCHEMA` in Angular unit tests?
- It suppresses errors from unknown elements and attributes in templates (Correct answer)
- It disables TypeScript type checking
- It skips validation of reactive form controls
- It prevents HttpClient errors from throwing
Correct answer: It suppresses errors from unknown elements and attributes in templates
NO_ERRORS_SCHEMA tells Angular to ignore unknown elements and attributes, simplifying shallow component testing without declaring child components.
Question 3: In Angular, what does `fakeAsync` combined with `tick()` allow you to test?
- Asynchronous code by simulating the passage of time (Correct answer)
- Synchronous pipes in isolation
- Lazy-loaded modules
- Router guard logic only
Correct answer: Asynchronous code by simulating the passage of time
fakeAsync wraps the test in a fake asynchronous zone, and tick() advances the virtual clock to resolve timers and Promises.
Question 4: Which method on a Jasmine spy allows you to define what value it returns when called?
- spy.and.returnValue() (Correct answer)
- spy.mock.returns()
- spy.stub.resolves()
- spy.configure.value()
Correct answer: spy.and.returnValue()
spy.and.returnValue() configures a Jasmine spy to return a specific value every time the spied function is invoked.
Question 5: When testing an Angular service that uses HttpClient, which module should be imported in TestBed?
- HttpClientTestingModule (Correct answer)
- HttpModule
- HttpClientModule
- RouterTestingModule
Correct answer: HttpClientTestingModule
HttpClientTestingModule replaces HttpClient with a mock backend (HttpTestingController) that lets you inspect and flush HTTP requests in tests.
Question 6: What Angular CLI command runs unit tests and watches for file changes?
- ng test (Correct answer)
- ng run tests
- ng spec --watch
- ng karma
Correct answer: ng test
ng test launches Karma, runs all spec files, and re-runs tests automatically when source files change.
Question 7: Which Karma configuration option specifies which browsers to use when running Angular tests?
- browsers (Correct answer)
- runners
- targets
- agents
Correct answer: browsers
The browsers array in karma.conf.js (e.g., ['Chrome', 'ChromeHeadless']) controls which browser environments Karma launches for test execution.
Which Angular testing utility method is used to trigger change detection manually in a component test?