Angular
Search…
Angular Unit Testing Interview Questions

Q. What is the difference between unit, integration, and e2e tests?

Unit Tests

Unit Tests sits at the base of the Testing Pyramid. This means they take lesser time to code and classes that you are testing should be more isolated. For example, a Login Feature normally has Validation and Authentication logic. They should be written in two separate classes like LoginValidator and LoginAuthenticator. Based on these two classes, you write test scripts.
When you try to test Networking functions, like in LoginAuthenticator, you should use Mock Response to test for both positive and negative responses.

Integration Tests

Integration Tests sits at the next level after Unit Tests. Here, you will use Real Network Responses, by hitting the real server endpoint, and test that the small units you have written are able to work together.

UI Tests

UI Testing automates repetitive tasks to ensure that your most critical UI interactions keep working as you’re adding new features or refactoring your app’s codebase. It may also help new developers to understand the app as they just need to run the UI Test once, he is able to see the automated test script running the app and interpret the app’s user journey from there.
Going back to the example of a Login Feature, UI Tests will
  1. 1.
    Tap on the Username.
  2. 2.
    Key in “Username”.
  3. 3.
    Tap on Password.
  4. 4.
    Key in “******”.
  5. 5.
    Tap on Submit.
Here the script will mock a success or failure response to move the app to the next screen, or show an alert box if failed.

End-to-End (E2E) Tests

Just like how Integration Tests works for Unit Tests, E2E Tests should test the user journeys of the app by using Real Network Response by hitting the Real server endpoints.

Q. How do you mock service to inject in a unit test?

a.) Resolving via TestBed The TestBed acts as a dummy Angular Module and we can configure it like one including with a set of providers like so:
1
TestBed.configureTestingModule({
2
providers: [AuthService]
3
});
Copied!
We can then ask the TestBed to resolve a token into a dependency using it’s an internal injector, like so:
1
testBedService = TestBed.get(AuthService);
Copied!
If most of our test specs need the same dependency mocked the same way we can resolve it once in the beforeEach function and mock it it there.
b.) Resolving via the inject function
1
it('Service injected via inject(...) and TestBed.get(...) should be the same instance',
2
inject([AuthService], (injectService: AuthService) => {
3
expect(injectService).toBe(testBedService);
4
})
5
);
Copied!
The inject function wraps the test spec function but lets us also inject dependencies using the parent injector in the TestBed.
1
inject(
2
[token1, token2, token2],
3
(dep1, dep2, dep3) => { }
4
)
Copied!
The first param is an array of tokens we want to resolve dependencies for, the second parameter is a function whose arguments are the resolved dependencies.
Using the inject function:
  • Makes it clear what dependencies each spec function uses.
  • If each test spec requires different mocks and spys this is a better solution that resolving it once per test suite.
c.) Overriding the components providers Before we create a component via the TestBed we can override it’s providers. Lets imagine we have a mock AuthService like so:
1
class MockAuthService extends AuthService {
2
isAuthenticated() {
3
return 'Mocked';
4
}
5
}
Copied!
We can override the components providers to use this mocked AuthService like so.
1
TestBed.overrideComponent(
2
LoginComponent,
3
{set: {providers: [{provide: AuthService, useClass: MockAuthService}]}}
4
);
Copied!
The syntax is pretty specific, it’s called a MetaDataOverride and it can have the properties set, add and remove. We use set to completely replace the providers array with the values we’ve set.
d.) Resolving via the component injector When the component is created since it has it’s own injector it will resolve the AuthService itself and not forward the request to it’s parent TestBed injector.
If we wanted to get the same instance of dependency that was passed to the component constructor we need to resolve using the component injector, we can do that through the component fixture like so:
1
componentService = fixture.debugElement.injector.get(AuthService);
Copied!
login.component.spec.ts
1
import { TestBed, ComponentFixture, inject } from '@angular/core/testing';
2
import { LoginComponent } from './login.component';
3
import { AuthService } from "./auth.service";
4
5
class MockAuthService extends AuthService {
6
isAuthenticated() {
7
return 'Mocked';
8
}
9
}
10
11
describe('Component: Login', () => {
12
13
let component: LoginComponent;
14
let fixture: ComponentFixture<LoginComponent>;
15
let testBedService: AuthService;
16
let componentService: AuthService;
17
18
beforeEach(() => {
19
20
// refine the test module by declaring the test component
21
TestBed.configureTestingModule({
22
declarations: [LoginComponent],
23
providers: [AuthService]
24
});
25
26
// Configure the component with another set of Providers
27
TestBed.overrideComponent(
28
LoginComponent,
29
{ set: { providers: [{ provide: AuthService, useClass: MockAuthService }] } }
30
);
31
32
// create component and test fixture
33
fixture = TestBed.createComponent(LoginComponent);
34
35
// get test component from the fixture
36
component = fixture.componentInstance;
37
38
// AuthService provided to the TestBed
39
testBedService = TestBed.get(AuthService);
40
41
// AuthService provided by Component, (should return MockAuthService)
42
componentService = fixture.debugElement.injector.get(AuthService);
43
});
44
45
it('Service injected via inject(...) and TestBed.get(...) should be the same instance',
46
inject([AuthService], (injectService: AuthService) => {
47
expect(injectService).toBe(testBedService);
48
})
49
);
50
51
it('Service injected via component should be and instance of MockAuthService', () => {
52
expect(componentService instanceof MockAuthService).toBeTruthy();
53
});
54
});
Copied!

Q. What's the difference between a unit test, integration test, and e2e?

  • End to End: A helper robot that behaves like a user to click around the app and verify that it functions correctly. Sometimes called "functional testing" or e2e.
  • Integration: Verify that several units work together in harmony.
  • Unit: Verify that individual, isolated parts work as expected.
  • Static: Catch typos and type errors as you write the code.

Q. What is Karma? What is the use of Angular?

Karma is a tool for executing source code against test code inside a browser environment. It supports the running of tests in each browser it’s configured for. Results are displayed on both the command line and on the browser for the developer to inspect which tests have passed or failed. Karma also watches the files and can trigger a test rerun whenever a file changes. At the root of the Angular project, we have the file karma.conf that’s used to configure Karma.
The contents should look something like this:
1
module.exports = function (config) {
2
config.set({
3
basePath: '',
4
frameworks: ['jasmine', '@angular/cli'],
5
plugins: [
6
require('karma-jasmine'),
7
require('karma-chrome-launcher'),
8
require('karma-jasmine-html-reporter'),
9
require('karma-coverage-istanbul-reporter'),
10
require('@angular/cli/plugins/karma')
11
],
12
client:{
13
clearContext: false // leave Jasmine Spec Runner output visible in browser
14
},
15
coverageIstanbulReporter: {
16
reports: [ 'html', 'lcovonly' ],
17
fixWebpackSourcePaths: true
18
},
19
angularCli: {
20
environment: 'dev'
21
},
22
reporters: ['progress', 'kjhtml'],
23
port: 9876,
24
colors: true,
25
logLevel: config.LOG_INFO,
26
autoWatch: true,
27
browsers: ['Chrome'],
28
singleRun: false
29
});
30
};
Copied!

Q. What is Jasmine? What is the Use in Angular?

Jasmine is a javascript testing framework that supports a software development practice called Behaviour Driven Development, or BDD for short. It’s a specific flavour of Test Driven Development (TDD).
Jasmine, and BDD in general, attempts to describe tests in a human readable format so that non-technical people can understand what is being tested.
For example if we wanted to test this function:
1
function message() {
2
return 'Hello world!';
3
}
Copied!
We would write a jasmine test spec like so:
1
describe('Hello world', () => {
2
it('says hello', () => {
3
expect(message())
4
.toEqual('Hello world!');
5
});
6
});
Copied!
  • The describe(string, function) function defines what we call a Test Suite, a collection of individual Test Specs.
  • The it(string, function) function defines an individual Test Spec, this contains one or more Test Expectations.
  • The expect(actual) expression is what we call an Expectation. In conjunction with a Matcher it describes an expected piece of behaviour in the application.
  • The matcher(expected) expression is what we call a Matcher. It does a boolean comparison with the expected value passed in vs. the actual value passed to the expect function, if they are false the spec fails.
Built-in matchers
1
expect(array).toContain(member);
2
expect(fn).toThrow(string);
3
expect(fn).toThrowError(string);
4
expect(instance).toBe(instance);
5
expect(mixed).toBeDefined();
6
expect(mixed).toBeFalsy();
7
expect(mixed).toBeNull();
8
expect(mixed).toBeTruthy();
9
expect(mixed).toBeUndefined();
10
expect(mixed).toEqual(mixed);
11
expect(mixed).toMatch(pattern);
12
expect(number).toBeCloseTo(number, decimalPlaces);
13
expect(number).toBeGreaterThan(number);
14
expect(number).toBeLessThan(number);
15
expect(number).toBeNaN();
16
expect(spy).toHaveBeenCalled();
17
expect(spy).toHaveBeenCalledTimes(number);
18
expect(spy).toHaveBeenCalledWith(...arguments);
Copied!
Setup and teardown
beforeAll: This function is called once, before all the specs in describe test suite are run. afterAll: This function is called once after all the specs in a test suite are finished. beforeEach: This function is called before each test specification, it function, has been run. afterEach: This function is called after each test specification has been run.
We might use these functions like so:
1
describe('Hello world', () => {
2
3
let expected = "";
4
5
beforeEach(() => {
6
expected = "Hello World";
7
});
8
9
afterEach(() => {
10
expected = "";
11
});
12
13
it('says hello', () => {
14
expect(message())
15
.toEqual(expected);
16
});
17
});
Copied!

Q. What is Protractor?

Protractor is an end-to-end test framework for Angular. It runs your tests inside a real browser, interacting with it as real person would. Unlike unit tests, where we test individual functions, here we test the entire logic. Protractor is able to fill in forms, click buttons and confirm that the expected data and styling is displayed in the HTML document. Just like Karma, Protractor has its own configuration file at the root of your Angular project, protractor.conf:
1
const { SpecReporter } = require('jasmine-spec-reporter');
2
3
exports.config = {
4
allScriptsTimeout: 11000,
5
specs: [
6
'./e2e/**/*.e2e-spec.ts'
7
],
8
capabilities: {
9
'browserName': 'chrome'
10
},
11
directConnect: true,
12
baseUrl: 'http://localhost:4200/',
13
framework: 'jasmine',
14
jasmineNodeOpts: {
15
showColors: true,
16
defaultTimeoutInterval: 30000,
17
print: function() {}
18
},
19
onPrepare() {
20
require('ts-node').register({
21
project: 'e2e/tsconfig.e2e.json'
22
});
23
jasmine.getEnv().addReporter(new SpecReporter({ spec: { displayStacktrace: true } }));
24
}
25
};
Copied!

Q. How to test a component's input as well as its outputs?

LoginComponent.ts
1
import {Component, EventEmitter, Input, Output} from '@angular/core';
2
3
export class User { (1)
4
constructor(public email: string, public password: string) {
5
}
6
}
7
8
@Component({
9
selector: 'app-login',
10
template: `
11
<form>
12
<label>Email</label>
13
<input type="email"
14
#email>
15
<label>Password</label>
16
<input type="password"
17
#password>
18
<button type="button" (2)
19
(click)="login(email.value, password.value)"
20
[disabled]="!enabled">Login
21
</button>
22
</form>
23
`
24
})
25
export class LoginComponent {
26
@Output() loggedIn = new EventEmitter<User>(); (3)
27
@Input() enabled = true; (4)
28
29
login(email, password) { (5)
30
console.log(`Login ${email} ${password}`);
31
if (email && password) {
32
console.log(`Emitting`);
33
this.loggedIn.emit(new User(email, password));
34
}
35
}
36
}
Copied!
  1. 1.
    We create a User class which holds the model of a logged in user.
  2. 2.
    The button is sometimes disabled depending on the enabled input property value and on clicking the button we call the login function.
  3. 3.
    The component has an output event called loggedIn.
  4. 4.
    The component has an input property called enabled.
  5. 5.
    In the login function we emit a new user model on the loggedIn event.
LoginComponent.spec.ts
1
describe('Component: Login', () => {
2
3
let component: LoginComponent;
4
let fixture: ComponentFixture<LoginComponent>;
5
let submitEl: DebugElement;
6
let loginEl: DebugElement;
7
let passwordEl: DebugElement;
8
9
beforeEach(() => {
10
11
TestBed.configureTestingModule({
12
declarations: [LoginComponent]
13
});
14
15
// create component and test fixture
16
fixture = TestBed.createComponent(LoginComponent);
17
18
// get test component from the fixture
19
component = fixture.componentInstance;
20
21
submitEl = fixture.debugElement.query(By.css('button'));
22
loginEl = fixture.debugElement.query(By.css('input[type=email]'));
23
passwordEl = fixture.debugElement.query(By.css('input[type=password]'));
24
});
25
});
Copied!
Testing @Inputs To test inputs we need to do things:
  • We need to be able to change the input property enabled on our component.
  • We need to check that the button is enabled or disabled depending on the value of our input property.
1
it('Setting enabled to false disables the submit button', () => {
2
component.enabled = false;
3
fixture.detectChanges();
4
expect(submitEl.nativeElement.disabled).toBeTruthy();
5
});
Copied!
Testing @Outputs
1
it('Entering email and password emits loggedIn event', () => {
2
let user: User;
3
loginEl.nativeElement.value = "[email protected]"; (1)
4
passwordEl.nativeElement.value = "123456";
5
6
component.loggedIn.subscribe((value) => user = value);
7
8
submitEl.triggerEventHandler('click', null); (2)
9
10
expect(user.email).toBe("[email protected]");
11
expect(user.password).toBe("123456");
12
});
Copied!
  1. 1.
    Setup data in our input controls.
  2. 2.
    Trigger a click on our submit button, this synchronously emits the user object in the subscribe callback!
Since the output event is actually an Observable we can subscribe to it and get a callback for every item emitted. We store the emitted value to a user object and then add some expectations on the user object.
We can test inputs by just setting values on a components input properties. We can test outputs by subscribing to an EventEmitters observable and storing the emitted values on local variables.

Q. Which of the following can be used to run unit tests in Angular?

  • Karma
  • Protractor

Q. Which of the following can be used to run end-to-end tests in Angular?

  • Karma
  • Protractor

Q. Test doubles are needed when writing which of the following?

  • Unit tests
  • End-to-end tests
  • Both of the above

Q. Which of the following will need Angular testing utilities for unit testing?

  • Services
  • Components
  • Both of the above

Q. Which of the following utility is used to create an Angular testing module which can be used to create module environment for the class one wants to test?

  • AngularTestUtil
  • NgTest
  • NgTestBed
  • TestBed
  • Services
  • Pipes
  • Both of the above
  • None of the above

Q. Karma test runner requires tests to be written with file having extension such as which of the following?

  • .test.ts
  • .spec.ts
  • Both of the above

Q. Which of the following TestBed method is used to create an Angular testing module which is used for creating a module environment for testing the class?

  • createTestModule
  • configureTestModule
  • configureTestingModule
  • createTestingModule

Q. Which of the following TestBed method is used to create an Angular component under test?

  • createComponent
  • createTestingComponent
  • configureComponent
  • configureTestingComponent

Q. It is OK to re-configure TestBed after calling createComponent API on TestBed.

  • True
  • False

Q. Types of Test in Angular?

The types of Testing looks are:
  1. 1.
    Unit Test
  2. 2.
    Integration Test
  3. 3.
    End to End (e2e) Test

Q. What is Unit Test in Angular?

The Unit Test is used to testing a single function, single components in Isolation. This is very fast.
In this Test, we are not able to say that everything is all right in the application. Just for a single Unit or function assure that working fine.
Example: app.component.ts
1
import { Component } from '@angular/core';
2
3
@Component({
4
selector: 'app-root',
5
templateUrl: './app.component.html',
6
styleUrls: ['./app.component.css']
7
})
8
export class AppComponent {
9
title = 'app';
10
}
Copied!
app.component.spec.ts
1
import { TestBed, async } from '@angular/core/testing';
2
import { AppComponent } from './app.component';
3
4
describe('AppComponent', () => {
5
beforeEach(async(() => {
6
TestBed.configureTestingModule({
7
declarations: [
8
AppComponent
9
],
10
}).compileComponents();
11
}));
12
13
it('should create the app', async(() => {
14
const fixture = TestBed.createComponent(AppComponent);
15
const app = fixture.debugElement.componentInstance;
16
17
expect(app).toBeTruthy();
18
}));
19
20
it(`should have as title 'app'`, async(() => {
21
const fixture = TestBed.createComponent(AppComponent);
22
const app = fixture.debugElement.componentInstance;
23
24
expect(app.title).toEqual('app');
25
}));
26
27
it('should render title in a h1 tag', async(() => {
28
const fixture = TestBed.createComponent(AppComponent);
29
fixture.detectChanges();
30
const compiled = fixture.debugElement.nativeElement;
31
32
expect(compiled.querySelector('h1').textContent).toContain('Welcome to app!');
33
}));
34
});
Copied!
app.component.html
1
<div style="text-align:center">
2
<h1> Welcome to {{title}}! </h1>
3
</div>
4
<h2>Here are some links to help you start: </h2>
5
<ul>
6
<li>
7
<h2><a target="_blank" rel="noopener" href="https://code-sample.com/">Tour of Examples</a></h2>
8
</li>
9
<li>
10
<h2><a target="_blank" rel="noopener" href="https://code-sample.com/">CLI Documentation</a></h2>
11
</li>
12
</ul>
Copied!

Q. What Is Integration Testing in Angular?

The Integration Testing is used to testing a component with templates and this testing containing more time as per comparison Unit Test.

Q. What is End-to-End Testing in Angular?

The End to End Testing is used to testing the entire application looks like -
  1. 1.
    All User Interactions
  2. 2.
    All Service Calls
  3. 3.
    Authentication/Authorization of app
  4. 4.
    Everything of App
This is the actual testing of your append it is fast action. Unit testing and Integrations testing will do as fake calls but e2e testing is done with your actual Services and APIs calls.
Recommended Unit Testing Tools – Angular 4/2 and Angular
  • Karma
  • Jasmine and
  • QUnit
Test Function – After installing everything as per your project requirements, CREATE your project. The following Steps –
  • ng new YourTestProject
  • ng install
  • ng serve/ng test
Note – If you are going to development then type ng server command and if you want to test your project, you should type ng test command. After type ng test command and press inter. It’s taking some time to installing everything in your project for test.

Q. What are the Test functions avilable in Angular?

  1. 1.
    describe() – Test suit (just a function)
  2. 2.
    it() - The spec or test
  3. 3.
    expect() - Expected outcome.
Triple Rule of Testing –
  1. 1.
    Arrange - Create and Initialize the Components
  2. 2.
    Act - Invoke the Methods/Functions of Components
  3. 3.
    Assert - Assert the expected outcome/behaviour

Q. What are the Best Practices in Unit Testing?

The quick list of best practices.
  • Use beforeEach() to Initialize the context for your tests.
  • Make sure the string descriptions you put in describe() and it() make sense as output
  • Use after() and afterEach() to clean-up your tests if there is any state that may bleed over.
  • If any one test is over 15 lines of code, you may need to refactor the test
1
import { TestBed, async } from '@angular/core/testing';
2
import { AppComponent } from './app.component';
3
4
//describe – Test suit (just a function)
5
describe('AppComponent', () => {
6
beforeEach(async(() => {
7
TestBed.configureTestingModule({
8
declarations: [AppComponent]
9
}).compileComponents();
10
}));
11
12
// it - The spec or test
13
it('should have hello property', function() {
14
const fixture = TestBed.createComponent(AppComponent);
15
const app = fixture.debugElement.componentInstance;
16
17
//expect – This Is For expected outcome.
18
expect(app.hello).toBe('Hello, Anil!');
19
});
20
});
Copied!
Example: Login Testing login.component.ts
1
import { Component, OnInit, EventEmitter,Input, Output, ViewEncapsulation } from '@angular/core';
2
3
@Component({
4
selector: 'app-login',
5
templateUrl: './login.component.html',
6
styleUrls: ['./login.component.css'],
7
encapsulation: ViewEncapsulation.None
8
})
9
export class LoginComponent implements OnInit {
10
11
@Output() loggedIn = new EventEmitter<User>();
12
@Input() enabled = true;
13
14
constructor() { }
15
16
ngOnInit() { }
17
18
login(email, password) {
19
if (email && password) {
20
this.loggedIn.emit(new User(email, password));
21
}
22
23
console.log(`Login ${email} ${password}`);
24
}
25
}
26
27
export class User {
28
constructor(public email: string, public password: string) {
29
}
30
}
Copied!
login.component.spec.ts
1
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
2
import {Component, DebugElement} from "@angular/core";
3
import {LoginComponent, User } from './login.component';
4
import {By} from "@angular/platform-browser";
5
6
describe('LoginComponent', () => {
7
let component: LoginComponent;
8
let fixture: ComponentFixture<LoginComponent>;
9
let submitElement: DebugElement;
10
let loginElement: DebugElement;
11
let passwordElement: DebugElement;
12
13
beforeEach(async(() => {
14
TestBed.configureTestingModule({
15
declarations: [LoginComponent]
16
})
17
.compileComponents();
18
}));
19
20
beforeEach(() => {
21
fixture = TestBed.createComponent(LoginComponent);
22
component = fixture.componentInstance;
23
fixture.detectChanges();
24
25
submitElement = fixture.debugElement.query(By.css('button'));
26
loginElement = fixture.debugElement.query(By.css('input[type=email]'));
27
passwordElement = fixture.debugElement.query(By.css('input[type=password]'));
28
});
29
30
it('Setting enabled to false disabled the submit button', () => {
31
component.enabled = false;
32
fixture.detectChanges();
33
34
//Expected outcome
35
expect(submitElement.nativeElement.disabled).toBeTruthy();
36
});
37
38
it('Setting enabled to true enables the submit button', () => {
39
component.enabled = true;
40
fixture.detectChanges();
41
42
//Expected outcome
43
expect(submitElement.nativeElement.disabled).toBeFalsy();
44
});
45
46
it('Entering email and password emits loggedIn event', () => {
47
let user: User;
48
49
loginElement.nativeElement.value = "[email protected]";
50
passwordElement.nativeElement.value = "$ystem!1356";
51
52
// Subscribe to the Observable and store the user in a local variable.
53
component.loggedIn.subscribe((value) => user = value);
54
55
// This sync emits the event and the subscribe callback gets executed above
56
submitElement.triggerEventHandler('click', null);
57
58
//Expected outcome
59
expect(user.email).toBe("[email protected]");
60
expect(user.password).toBe("$ystem!1356");
61
});
62
63
});
Copied!
login.component.html
1
<form>
2
<label>Email</label>
3
<input type="email" #email>
4
<label>Password</label>
5
<input type="password" #password>
6
<button type="button"
7
(click)="login(email.value, password.value)"
8
[disabled]="!enabled">Login
9
</button>
10
</form>
Copied!
1
ng test
Copied!

Q. How do you unit test service with a dependency?

Using TestBed
1
TestBed.configureTestingModule({
2
providers: [AuthService]
3
});
Copied!

Q. How code coverage works in angular 7?

The CLI can run unit tests and create code coverage reports. Code coverage reports show you any parts of our code base that may not be properly tested by your unit tests.
To generate a coverage report run the following command in the root of your project.
1
ng test --code-coverage
Copied!
When the tests are complete, the command creates a new /coverage folder in the project. Open the index.html file to see a report with your source code and code coverage values.
If you want to create code-coverage reports every time you test, you can set the following option in the CLI configuration file, angular.json:
1
"test": {
2
"options": {
3
"codeCoverage": true
4
}
5
}
Copied!
Code coverage enforcement
The code coverage percentages let you estimate how much of your code is tested. If your team decides on a set minimum amount to be unit tested, you can enforce this minimum with the Angular CLI.
For example, suppose you want the code base to have a minimum of 80% code coverage. To enable this, open the Karma test platform configuration file, karma.conf.js, and add the following in the coverageIstanbulReporter: key.
1
coverageIstanbulReporter: {
2
reports: [ 'html', 'lcovonly' ],
3
fixWebpackSourcePaths: true,
4
thresholds: {
5
statements: 80,
6
lines: 80,
7
branches: 80,
8
functions: 80
9
}
10
}
Copied!
The thresholds property causes the tool to enforce a minimum of 80% code coverage when the unit tests are run in the project.↥ back to top

Q. Explain Unit Testing using Mocha and Chai in Angular 7?

Installation
1
npm install chai mocha ts-node @types/chai @types/mocha --save-dev
Copied!
Mocha is a JavaScript test framework running on Node.js and in the browser. Mocha allows asynchronous testing, test coverage reports, and use of any assertion library. Mocha gives us a Suite for describing, running and building tests but it does not give us a way to check values.
Chai is a BDD / TDD assertion library for NodeJS and the browser that can be delightfully paired with any javascript testing framework.
Basically, mocha is a framework and chai is a library. Let's go a little deeper in mocha. Mocha uses hooks to organize its structure.
  • describe(): It's used to group, which you can nest as deep;
  • it(): It's the test case;
  • before(): It's a hook to run before the first it() or describe();
  • beforeEach(): It’s a hook to run before each it() or describe();
  • after(): It’s a hook to run after it() or describe();
  • afterEach(): It’s a hook to run after each it() or describe();
Scenario 1: One test case
In this case, we can just call a solitary it(), mocha will run this only test.
1
it('Homer should drink beer', () => {
2
/** Test cases */
3
})
Copied!
Scenario 2: A nested test case
In this case, we can nest some describes() hooks and finally call it() to execute the test.
1
describe('Abraham Simpson', () => {
2
describe('Homer Simpson', () => {
3
describe('Bart Simpson', () => {
4
it('Bart should skate', () => {
5
/** Test cases */
6
})
7
})
8
})
9
})
Copied!
Scenario 3: Two test cases in one test
Here, inside the describe() we have two it() that will execute the tests.
1
describe('Homer Simpson', () => {
2
it('Bart should skate', () => {
3
/** Test cases for Bart */
4
})
5
it('Lisa should play sax', () => {
6
/** Test cases for Lisa */
7
})
8
})
Copied!
Scenario 4: Run just once before the first test case
In this scenario, before the first it() mocha will execute what is inside before(), but only once.
1
describe('Springfield', () => {
2
before(() => {
3
console.log('Marge calls Barge and Lisa (you see this only once)')
4
})
5
it('Bart should hear his mother', () => {
6
/** Test cases */
7
})
8
it('Lisa should hear her mother', () => {
9
/** Test cases */
10
})
11
})
Copied!
Scenario 5: Run once before each test case
On the contrary of before(), beforeEach() is executed each time for each it() [or describe()] that we have. If we have one it(), it will be executed just once. if we have two it() it will be executed twice and so go on.
1
describe('Springfield', () => {
2
beforeEach(() => {
3
console.log('Marge calls Barge and Lisa (you see this twice)')
4
})
5
it('Bart should hear his mother', () => {
6
/** Test cases */
7
})
8
it('Lisa should hear her mother', () => {
9
/** Test cases */
10
})
11
})
Copied!
Scenario 6: Two tests in a big test
In this last scenario, mocha will nest the describe() and execute it().
1
describe('Homer Simpson', () => {
2
describe('Bart Simpson', () => {
3
it('Bart should skate', () => {
4
/** Test cases */
5
})
6
})
7
describe('Lisa Simpson', () => {
8
it('Lisa should play sax', () => {
9
/** Test cases */
10
})
11
})
12
})
Copied!
Run
1
$ yarn mocha
Copied!
Q. What are some of the different tests types you can write?
Q. How do you mock a service to inject in an integration test?
Q. How do you mock a module in an integration test?
Q. How do you test a component that has a dependency to an async service?
Q. What is the difference between 'async()' and 'fakeAsync()'?
Copy link
Contents
Q. What is the difference between unit, integration, and e2e tests?
Q. How do you mock service to inject in a unit test?
Q. What's the difference between a unit test, integration test, and e2e?
Q. What is Karma? What is the use of Angular?
Q. What is Jasmine? What is the Use in Angular?
Q. What is Protractor?
Q. How to test a component's input as well as its outputs?
Q. Which of the following can be used to run unit tests in Angular?
Q. Which of the following can be used to run end-to-end tests in Angular?
Q. Test doubles are needed when writing which of the following?
Q. Which of the following will need Angular testing utilities for unit testing?
Q. Which of the following utility is used to create an Angular testing module which can be used to create module environment for the class one wants to test?
Q. It is recommended to write isolated unit tests for which of the following?
Q. Karma test runner requires tests to be written with file having extension such as which of the following?
Q. Which of the following TestBed method is used to create an Angular testing module which is used for creating a module environment for testing the class?
Q. Which of the following TestBed method is used to create an Angular component under test?
Q. It is OK to re-configure TestBed after calling createComponent API on TestBed.
Q. Types of Test in Angular?
Q. What is Unit Test in Angular?
Q. What Is Integration Testing in Angular?
Q. What is End-to-End Testing in Angular?
Q. What are the Test functions avilable in Angular?
Q. What are the Best Practices in Unit Testing?
Q. How do you unit test service with a dependency?
Q. How code coverage works in angular 7?
Q. Explain Unit Testing using Mocha and Chai in Angular 7?