// code
function hello(name) {
return `Hello, ${name}!`;
}
// test
function testHello() {
const actual = hello('Tim');
console.assert(actual, 'Hello, Tim!')
}
// test running
testHello(); // nothing happens!
app.component.ts
app.component.spec.ts
app.component.html
Karma is essentially a tool which spawns a web server that executes source code against test code for each of the browsers connected.
The results of each test against each browser are examined and displayed via the command line to the developer such that they can see which browsers and tests passed or failed.
$ yarn add --dev jest jest-preset-angular @types/jest
"jest": {
"preset": "jest-preset-angular",
"setupTestFrameworkScriptFile": "<rootDir>/src/setupJest.ts"
}
import 'jest-preset-angular';
import './jestGlobalMocks';
Object.defineProperty(window, 'getComputedStyle', {
value: () => ['-webkit-appearance']
});
$ jest
1. Install npm dependecies
2. package.json
3. src/setupJest.js
4. src/jestGlobalMocks.js
5. Done!
import { Input, Component } from '@angular/core';
@Component({
selector: 'flight-info',
template: `
<mat-list-item>
<div class="fare">
<span class="airport">{{ flight.departure }}</span>
<small>{{ flight.departureDatetime | date:'short' }}</small>
</div>
<div class="fare">
<span class="airport">{{ flight.destination }}</span>
<small>{{ flight.arrivalDatetime | date:'short' }}</small>
</div>
</mat-list-item>
`,
styleUrls: [ './flight-info.component.css' ]
})
export class FlightInfoComponent {
@Input() flight;
}
it('Should display a flight from DUB to WRO', () => {
component.flight = {
flightNumber: 'FR153',
departure: 'DUB',
destination: 'WRO',
departureDatetime: '2018-06-15T17:25:00',
arrivalDatetime: '2018-06-15T21:00:00'
};
fixture.detectChanges();
expect(fixture).toMatchSnapshot();
});
exports[`FlightInfoComponent Should display a flight from DUB to WRO 1`] = `
<flight-info
flight={[Function Object]}
>
<mat-list-item
class="mat-list-item"
>
<div
class="mat-list-item-content"
>
<div
class="mat-list-item-ripple mat-ripple"
mat-ripple=""
ng-reflect-disabled="true"
ng-reflect-trigger="[object HTMLUnknownElement]"
/>
<div
class="mat-list-text"
/>
<div
class="fare"
>
<span
class="airport"
>
DUB
</span>
<small>
6/15/18, 5:25 PM
</small>
</div>
<div
class="fare"
>
<span
class="airport"
>
WRO
</span>
<small>
6/15/18, 9:00 PM
</small>
</div>
</div>
</mat-list-item>
</flight-info>
`;
1. https://jestjs.io/ - Delightful JavaScript Testing
2. https://www.xfive.co/blog/testing-angular-faster-jest/ - TESTING ANGULAR FASTER WITH JEST by Michal Pierzchala
3. https://izifortune.com/snapshot-testing-angular-applications/ - Snapshot testing Angular applications by Fabrizio Fortunato
Artsiom Mezin