Refs
Why unit tests?
Understanding concepts
⚠️ This is my personal note, it may be not a perfect (or “right”) way!
👉 Good to read: Towards Better Testing In Angular. Part 1 — Mocking Child Components | by Abdul Wahab Rafehi | Medium
💡 Recommended in the Angular Testing Guide, is to manually mock (or stub) components
If cannot find child component errors? (source)
declarations: [ChildComponent]⇒ BUT it's not isolated, it depends onChildComponent!- Cons: If in
ChildComponent, we add some dependency ⇒ not working
- Use
schemas: NO_ERRORS_SCHEMAto tell the compiler to ignore any elements or attributes it isn’t familiar with - Cons: if inside parent, we mispelling
<child></chidl>or any wong things with child components ⇒ it still works but not really!! ⇒ There will be something wrong until we actually run the app. Difficult to test@Inputand@Output.
- Mock / Stub child component ⇒ ensure to have the same selector. ⇒ có thể tạo 1 cái "mock" class của
ChildComponentbằng 1 file.stub - Cons: it's verbose + shortcoming if there are many inputs and outputs. It requires us to remember to change the stub each time we change the real component
- Using
ng-mock
Refs:
- Test parent and child components when passing data with input binding ⇒ defind in parent a simple child component (like the real one) + mocking a hero input if you wanna test child component.
- (read later) https://stackoverflow.com/questions/40541123/how-to-unit-test-if-an-angular-2-component-contains-another-component
If a component depends on many services, you need to create mocks of these services in which the function/properties you need to use in your component.
👉 Official doc (search for "The following WelcomeComponent depends on the UserService to know the name of the user to greet.")
👉🏻 Official doc: Angular - Testing services
👇🏻 Source.
The input
questions (in child) takes value from myQuestions (in parent) ⇒ Life cycle hooks: check data-bound input > ngOnInit > other components.👉🏻 Form & submit testing example (the same source as above): returned payload, setValue and submit,... + codes
(src) A spy allows us to “spy” on a function and track attributes about it such as whether or not it was called, how many times it was called, and with which arguments it was called.
✳️ NullInjectorError: No provider for HttpClient!
✳️ NullInjectorError: No provider for AngularFireDatabase!
Check thử xem nó xuất hiện lỗi từ service/component/module nào, ví dụ
Suy ra: chỉ cần mock cái
BotSessionService là ok!✳️ NullInjectorError: No provider for Router!
→ Just use a fake
Router✳️ NullInjectorError (in general)
We can use