├── src
├── assets
│ └── .gitkeep
├── app
│ ├── models
│ │ └── movies.ts
│ ├── app.component.html
│ ├── app.component.css
│ ├── app.component.ts
│ ├── movies
│ │ ├── movies.component.html
│ │ ├── movies.component.css
│ │ ├── movies.component.store.ts
│ │ ├── movies.component.ts
│ │ ├── movies.component.store.spec.ts
│ │ └── movies.component.spec.ts
│ └── app.module.ts
├── environments
│ ├── environment.prod.ts
│ └── environment.ts
├── favicon.ico
├── styles.css
├── index.html
├── main.ts
├── test.ts
└── polyfills.ts
├── README.md
├── .editorconfig
├── e2e
├── src
│ ├── app.po.ts
│ └── app.e2e-spec.ts
├── tsconfig.json
└── protractor.conf.js
├── tsconfig.app.json
├── tsconfig.spec.json
├── .github
└── workflows
│ └── ci.yml
├── tsconfig.json
├── .gitignore
├── .browserslistrc
├── karma.conf.js
├── package.json
├── tslint.json
└── angular.json
/src/assets/.gitkeep:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/src/app/models/movies.ts:
--------------------------------------------------------------------------------
1 | export interface Movie {
2 | id: number;
3 | name: string;
4 | }
5 |
--------------------------------------------------------------------------------
/src/environments/environment.prod.ts:
--------------------------------------------------------------------------------
1 | export const environment = {
2 | production: true
3 | };
4 |
--------------------------------------------------------------------------------
/src/favicon.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ngfelixl/ngrx-component-store-testing/HEAD/src/favicon.ico
--------------------------------------------------------------------------------
/src/app/app.component.html:
--------------------------------------------------------------------------------
1 |
Movies Component Store Demo
2 |
--------------------------------------------------------------------------------
/src/app/app.component.css:
--------------------------------------------------------------------------------
1 | .toolbar {
2 | padding: 20px;
3 | background-color: steelblue;
4 | color: white;
5 | font-size: 18px;
6 | }
--------------------------------------------------------------------------------
/src/styles.css:
--------------------------------------------------------------------------------
1 | /* You can add global styles to this file, and also import other style files */
2 | body {
3 | margin: 0;
4 | font-family: Roboto, sans-serif, Helvetica, Arial;
5 | }
--------------------------------------------------------------------------------
/src/app/app.component.ts:
--------------------------------------------------------------------------------
1 | import { ChangeDetectionStrategy, Component } from '@angular/core';
2 |
3 | @Component({
4 | selector: 'app-root',
5 | templateUrl: './app.component.html',
6 | styleUrls: ['./app.component.css'],
7 | changeDetection: ChangeDetectionStrategy.OnPush
8 | })
9 | export class AppComponent {}
10 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # NgrxComponentStoreTesting
2 |
3 | This is an example project for unit testing NgRX component store components. There are tests for the
4 | component store itself and also integration tests for the component making use of the component store.
5 |
6 | Related issue: [ngrx/platform, issue #2767](https://github.com/ngrx/platform/issues/2767).
--------------------------------------------------------------------------------
/.editorconfig:
--------------------------------------------------------------------------------
1 | # Editor configuration, see https://editorconfig.org
2 | root = true
3 |
4 | [*]
5 | charset = utf-8
6 | indent_style = space
7 | indent_size = 2
8 | insert_final_newline = true
9 | trim_trailing_whitespace = true
10 |
11 | [*.ts]
12 | quote_type = single
13 |
14 | [*.md]
15 | max_line_length = off
16 | trim_trailing_whitespace = false
17 |
--------------------------------------------------------------------------------
/e2e/src/app.po.ts:
--------------------------------------------------------------------------------
1 | import { browser, by, element } from 'protractor';
2 |
3 | export class AppPage {
4 | navigateTo(): Promise {
5 | return browser.get(browser.baseUrl) as Promise;
6 | }
7 |
8 | getTitleText(): Promise {
9 | return element(by.css('app-root .content span')).getText() as Promise;
10 | }
11 | }
12 |
--------------------------------------------------------------------------------
/e2e/tsconfig.json:
--------------------------------------------------------------------------------
1 | /* To learn more about this file see: https://angular.io/config/tsconfig. */
2 | {
3 | "extends": "../tsconfig.json",
4 | "compilerOptions": {
5 | "outDir": "../out-tsc/e2e",
6 | "module": "commonjs",
7 | "target": "es2018",
8 | "types": [
9 | "jasmine",
10 | "jasminewd2",
11 | "node"
12 | ]
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/tsconfig.app.json:
--------------------------------------------------------------------------------
1 | /* To learn more about this file see: https://angular.io/config/tsconfig. */
2 | {
3 | "extends": "./tsconfig.json",
4 | "compilerOptions": {
5 | "outDir": "./out-tsc/app",
6 | "types": []
7 | },
8 | "files": [
9 | "src/main.ts",
10 | "src/polyfills.ts"
11 | ],
12 | "include": [
13 | "src/**/*.d.ts"
14 | ]
15 | }
16 |
--------------------------------------------------------------------------------
/src/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | NgrxComponentStoreTesting
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
--------------------------------------------------------------------------------
/tsconfig.spec.json:
--------------------------------------------------------------------------------
1 | /* To learn more about this file see: https://angular.io/config/tsconfig. */
2 | {
3 | "extends": "./tsconfig.json",
4 | "compilerOptions": {
5 | "outDir": "./out-tsc/spec",
6 | "types": [
7 | "jasmine"
8 | ]
9 | },
10 | "files": [
11 | "src/test.ts",
12 | "src/polyfills.ts"
13 | ],
14 | "include": [
15 | "src/**/*.spec.ts",
16 | "src/**/*.d.ts"
17 | ]
18 | }
19 |
--------------------------------------------------------------------------------
/src/main.ts:
--------------------------------------------------------------------------------
1 | import { enableProdMode } from '@angular/core';
2 | import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
3 |
4 | import { AppModule } from './app/app.module';
5 | import { environment } from './environments/environment';
6 |
7 | if (environment.production) {
8 | enableProdMode();
9 | }
10 |
11 | platformBrowserDynamic().bootstrapModule(AppModule)
12 | .catch(err => console.error(err));
13 |
--------------------------------------------------------------------------------
/src/app/movies/movies.component.html:
--------------------------------------------------------------------------------
1 |
5 |
6 |
7 | -
8 | {{ movie.name }}
9 |
10 |
11 |
--------------------------------------------------------------------------------
/.github/workflows/ci.yml:
--------------------------------------------------------------------------------
1 | name: Node.js CI
2 |
3 | on: [push]
4 |
5 | jobs:
6 | build:
7 |
8 | runs-on: ubuntu-latest
9 |
10 | steps:
11 | - uses: actions/checkout@v2
12 | - name: Use Node.js
13 | uses: actions/setup-node@v1
14 | with:
15 | node-version: '12.x'
16 | - run: npm ci
17 | - run: npm run build --if-present
18 | - run: npm test -- --configuration=ci
19 | env:
20 | CI: true
--------------------------------------------------------------------------------
/tsconfig.json:
--------------------------------------------------------------------------------
1 | /* To learn more about this file see: https://angular.io/config/tsconfig. */
2 | {
3 | "compileOnSave": false,
4 | "compilerOptions": {
5 | "baseUrl": "./",
6 | "outDir": "./dist/out-tsc",
7 | "sourceMap": true,
8 | "declaration": false,
9 | "downlevelIteration": true,
10 | "experimentalDecorators": true,
11 | "moduleResolution": "node",
12 | "importHelpers": true,
13 | "target": "es2015",
14 | "module": "es2020",
15 | "lib": [
16 | "es2018",
17 | "dom"
18 | ]
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/src/app/movies/movies.component.css:
--------------------------------------------------------------------------------
1 | form {
2 | display: flex;
3 | max-width: 500px;
4 | margin: 20px auto;
5 | justify-content: stretch;
6 | }
7 |
8 | form input {
9 | flex: 1;
10 | padding: 8px;
11 | margin-right: 8px;
12 | }
13 |
14 | button {
15 | cursor: pointer;
16 | }
17 |
18 | ul {
19 | max-width: 500px;
20 | margin: 20px auto;
21 | justify-content: stretch;
22 | list-style: none;
23 | padding: 0;
24 | }
25 |
26 | .movie {
27 | display: flex;
28 | justify-content: stretch;
29 | margin: 8px 0;
30 | }
31 |
32 | .movie span {
33 | flex: 1 1 0;
34 | }
35 |
36 | .movie button {
37 | flex: 0 0 auto;
38 | }
--------------------------------------------------------------------------------
/src/app/app.module.ts:
--------------------------------------------------------------------------------
1 | import { BrowserModule } from '@angular/platform-browser';
2 | import { NgModule } from '@angular/core';
3 |
4 | import { AppComponent } from './app.component';
5 | import { MoviesComponent } from './movies/movies.component';
6 | import { ReactiveFormsModule } from '@angular/forms';
7 | import { MoviesStore } from './movies/movies.component.store';
8 |
9 | @NgModule({
10 | declarations: [
11 | AppComponent,
12 | MoviesComponent
13 | ],
14 | imports: [
15 | BrowserModule,
16 | ReactiveFormsModule
17 | ],
18 | providers: [MoviesStore],
19 | bootstrap: [AppComponent]
20 | })
21 | export class AppModule { }
22 |
--------------------------------------------------------------------------------
/src/environments/environment.ts:
--------------------------------------------------------------------------------
1 | // This file can be replaced during build by using the `fileReplacements` array.
2 | // `ng build --prod` replaces `environment.ts` with `environment.prod.ts`.
3 | // The list of file replacements can be found in `angular.json`.
4 |
5 | export const environment = {
6 | production: false
7 | };
8 |
9 | /*
10 | * For easier debugging in development mode, you can import the following file
11 | * to ignore zone related error stack frames such as `zone.run`, `zoneDelegate.invokeTask`.
12 | *
13 | * This import should be commented out in production mode because it will have a negative impact
14 | * on performance if an error is thrown.
15 | */
16 | // import 'zone.js/dist/zone-error'; // Included with Angular CLI.
17 |
--------------------------------------------------------------------------------
/e2e/src/app.e2e-spec.ts:
--------------------------------------------------------------------------------
1 | import { AppPage } from './app.po';
2 | import { browser, logging } from 'protractor';
3 |
4 | describe('workspace-project App', () => {
5 | let page: AppPage;
6 |
7 | beforeEach(() => {
8 | page = new AppPage();
9 | });
10 |
11 | it('should display welcome message', () => {
12 | page.navigateTo();
13 | expect(page.getTitleText()).toEqual('ngrx-component-store-testing app is running!');
14 | });
15 |
16 | afterEach(async () => {
17 | // Assert that there are no errors emitted from the browser
18 | const logs = await browser.manage().logs().get(logging.Type.BROWSER);
19 | expect(logs).not.toContain(jasmine.objectContaining({
20 | level: logging.Level.SEVERE,
21 | } as logging.Entry));
22 | });
23 | });
24 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # See http://help.github.com/ignore-files/ for more about ignoring files.
2 |
3 | # compiled output
4 | /dist
5 | /tmp
6 | /out-tsc
7 | # Only exists if Bazel was run
8 | /bazel-out
9 |
10 | # dependencies
11 | /node_modules
12 |
13 | # profiling files
14 | chrome-profiler-events*.json
15 | speed-measure-plugin*.json
16 |
17 | # IDEs and editors
18 | /.idea
19 | .project
20 | .classpath
21 | .c9/
22 | *.launch
23 | .settings/
24 | *.sublime-workspace
25 |
26 | # IDE - VSCode
27 | .vscode/*
28 | !.vscode/settings.json
29 | !.vscode/tasks.json
30 | !.vscode/launch.json
31 | !.vscode/extensions.json
32 | .history/*
33 |
34 | # misc
35 | /.sass-cache
36 | /connect.lock
37 | /coverage
38 | /libpeerconnection.log
39 | npm-debug.log
40 | yarn-error.log
41 | testem.log
42 | /typings
43 |
44 | # System Files
45 | .DS_Store
46 | Thumbs.db
47 |
--------------------------------------------------------------------------------
/src/test.ts:
--------------------------------------------------------------------------------
1 | // This file is required by karma.conf.js and loads recursively all the .spec and framework files
2 |
3 | import 'zone.js/dist/zone-testing';
4 | import { getTestBed } from '@angular/core/testing';
5 | import {
6 | BrowserDynamicTestingModule,
7 | platformBrowserDynamicTesting
8 | } from '@angular/platform-browser-dynamic/testing';
9 |
10 | declare const require: {
11 | context(path: string, deep?: boolean, filter?: RegExp): {
12 | keys(): string[];
13 | (id: string): T;
14 | };
15 | };
16 |
17 | // First, initialize the Angular testing environment.
18 | getTestBed().initTestEnvironment(
19 | BrowserDynamicTestingModule,
20 | platformBrowserDynamicTesting()
21 | );
22 | // Then we find all the tests.
23 | const context = require.context('./', true, /\.spec\.ts$/);
24 | // And load the modules.
25 | context.keys().map(context);
26 |
--------------------------------------------------------------------------------
/src/app/movies/movies.component.store.ts:
--------------------------------------------------------------------------------
1 | import { Injectable } from '@angular/core';
2 | import { ComponentStore } from '@ngrx/component-store';
3 | import { Observable } from 'rxjs';
4 | import { Movie } from '../models/movies';
5 |
6 | export interface MoviesState {
7 | movies: Movie[];
8 | }
9 |
10 | @Injectable()
11 | export class MoviesStore extends ComponentStore {
12 | constructor() {
13 | super({movies: []});
14 | }
15 |
16 | readonly addMovie = this.updater((state, movie: Omit) => ({
17 | movies: [...state.movies, {
18 | id: Math.max(...state.movies.map(m => m.id), 0) + 1,
19 | ...movie
20 | }],
21 | }));
22 |
23 | readonly deleteMovie = this.updater((state, id: number) => ({
24 | movies: state.movies.filter(movie => movie.id !== id)
25 | }));
26 |
27 | readonly movies$: Observable = this.select(state => state.movies);
28 | }
29 |
--------------------------------------------------------------------------------
/.browserslistrc:
--------------------------------------------------------------------------------
1 | # This file is used by the build system to adjust CSS and JS output to support the specified browsers below.
2 | # For additional information regarding the format and rule options, please see:
3 | # https://github.com/browserslist/browserslist#queries
4 |
5 | # For the full list of supported browsers by the Angular framework, please see:
6 | # https://angular.io/guide/browser-support
7 |
8 | # You can see what browsers were selected by your queries by running:
9 | # npx browserslist
10 |
11 | last 1 Chrome version
12 | last 1 Firefox version
13 | last 2 Edge major versions
14 | last 2 Safari major versions
15 | last 2 iOS major versions
16 | Firefox ESR
17 | not IE 9-10 # Angular support for IE 9-10 has been deprecated and will be removed as of Angular v11. To opt-in, remove the 'not' prefix on this line.
18 | not IE 11 # Angular supports IE 11 only as an opt-in. To opt-in, remove the 'not' prefix on this line.
19 |
--------------------------------------------------------------------------------
/e2e/protractor.conf.js:
--------------------------------------------------------------------------------
1 | // @ts-check
2 | // Protractor configuration file, see link for more information
3 | // https://github.com/angular/protractor/blob/master/lib/config.ts
4 |
5 | const { SpecReporter, StacktraceOption } = require('jasmine-spec-reporter');
6 |
7 | /**
8 | * @type { import("protractor").Config }
9 | */
10 | exports.config = {
11 | allScriptsTimeout: 11000,
12 | specs: [
13 | './src/**/*.e2e-spec.ts'
14 | ],
15 | capabilities: {
16 | browserName: 'chrome'
17 | },
18 | directConnect: true,
19 | baseUrl: 'http://localhost:4200/',
20 | framework: 'jasmine',
21 | jasmineNodeOpts: {
22 | showColors: true,
23 | defaultTimeoutInterval: 30000,
24 | print: function() {}
25 | },
26 | onPrepare() {
27 | require('ts-node').register({
28 | project: require('path').join(__dirname, './tsconfig.json')
29 | });
30 | jasmine.getEnv().addReporter(new SpecReporter({
31 | spec: {
32 | displayStacktrace: StacktraceOption.PRETTY
33 | }
34 | }));
35 | }
36 | };
--------------------------------------------------------------------------------
/src/app/movies/movies.component.ts:
--------------------------------------------------------------------------------
1 | import { ChangeDetectionStrategy, Component, OnInit } from '@angular/core';
2 | import { FormControl, FormGroup, Validators } from '@angular/forms';
3 | import { Movie } from '../models/movies';
4 | import { MoviesStore } from './movies.component.store';
5 |
6 | @Component({
7 | selector: 'app-movies',
8 | templateUrl: './movies.component.html',
9 | styleUrls: ['./movies.component.css'],
10 | providers: [MoviesStore],
11 | changeDetection: ChangeDetectionStrategy.OnPush
12 | })
13 | export class MoviesComponent implements OnInit {
14 | addMovieForm: FormGroup;
15 | movies$ = this.moviesStore.movies$;
16 |
17 | constructor(private readonly moviesStore: MoviesStore) {
18 | this.addMovieForm = new FormGroup({
19 | name: new FormControl(null, Validators.required)
20 | });
21 | }
22 |
23 | ngOnInit(): void {
24 | this.moviesStore.setState({movies: []});
25 | }
26 |
27 | addMovie(): void {
28 | const movie: Omit = this.addMovieForm.value;
29 | this.addMovieForm.reset();
30 | this.moviesStore.addMovie(movie);
31 | }
32 |
33 | deleteMovie(id: number): void {
34 | this.moviesStore.deleteMovie(id);
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/karma.conf.js:
--------------------------------------------------------------------------------
1 | // Karma configuration file, see link for more information
2 | // https://karma-runner.github.io/1.0/config/configuration-file.html
3 |
4 | module.exports = function (config) {
5 | config.set({
6 | basePath: '',
7 | frameworks: ['jasmine', '@angular-devkit/build-angular'],
8 | plugins: [
9 | require('karma-jasmine'),
10 | require('karma-chrome-launcher'),
11 | require('karma-jasmine-html-reporter'),
12 | require('karma-coverage-istanbul-reporter'),
13 | require('@angular-devkit/build-angular/plugins/karma')
14 | ],
15 | client: {
16 | clearContext: false // leave Jasmine Spec Runner output visible in browser
17 | },
18 | coverageIstanbulReporter: {
19 | dir: require('path').join(__dirname, './coverage/ngrx-component-store-testing'),
20 | reports: ['html', 'lcovonly', 'text-summary'],
21 | fixWebpackSourcePaths: true
22 | },
23 | reporters: ['progress', 'kjhtml'],
24 | port: 9876,
25 | colors: true,
26 | logLevel: config.LOG_INFO,
27 | autoWatch: true,
28 | browsers: ['Chrome', 'ChromeHeadless', 'ChromeHeadlessCI'],
29 | customLaunchers: {
30 | ChromeHeadlessCI: {
31 | base: 'ChromeHeadless',
32 | flags: ['--no-sandbox']
33 | }
34 | },
35 | singleRun: false,
36 | restartOnFileChange: true
37 | });
38 | };
39 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "ngrx-component-store-testing",
3 | "version": "0.0.0",
4 | "scripts": {
5 | "ng": "ng",
6 | "start": "ng serve",
7 | "build": "ng build",
8 | "test": "ng test",
9 | "lint": "ng lint",
10 | "e2e": "ng e2e"
11 | },
12 | "private": true,
13 | "dependencies": {
14 | "@angular/animations": "~10.1.6",
15 | "@angular/common": "~10.1.6",
16 | "@angular/compiler": "~10.1.6",
17 | "@angular/core": "~10.1.6",
18 | "@angular/forms": "~10.1.6",
19 | "@angular/platform-browser": "~10.1.6",
20 | "@angular/platform-browser-dynamic": "~10.1.6",
21 | "@angular/router": "~10.1.6",
22 | "@ngrx/component-store": "^10.0.1",
23 | "rxjs": "~6.6.0",
24 | "tslib": "^2.0.0",
25 | "zone.js": "~0.10.2"
26 | },
27 | "devDependencies": {
28 | "@angular-devkit/build-angular": "~0.1001.7",
29 | "@angular/cli": "~10.1.7",
30 | "@angular/compiler-cli": "~10.1.6",
31 | "@types/node": "^12.11.1",
32 | "@types/jasmine": "~3.5.0",
33 | "@types/jasminewd2": "~2.0.3",
34 | "codelyzer": "^6.0.0",
35 | "jasmine-core": "~3.6.0",
36 | "jasmine-spec-reporter": "~5.0.0",
37 | "karma": "~5.0.0",
38 | "karma-chrome-launcher": "~3.1.0",
39 | "karma-coverage-istanbul-reporter": "~3.0.2",
40 | "karma-jasmine": "~4.0.0",
41 | "karma-jasmine-html-reporter": "^1.5.0",
42 | "protractor": "~7.0.0",
43 | "ts-node": "~8.3.0",
44 | "tslint": "~6.1.0",
45 | "typescript": "~4.0.2"
46 | }
47 | }
48 |
--------------------------------------------------------------------------------
/src/app/movies/movies.component.store.spec.ts:
--------------------------------------------------------------------------------
1 | import { MoviesStore } from './movies.component.store';
2 |
3 | describe('MoviesComponentStore', () => {
4 |
5 | describe('addMovie reducer', () => {
6 | it('should add a movie to the store', (done) => {
7 | const moviesStore = new MoviesStore();
8 | moviesStore.setState({ movies: [] });
9 |
10 | moviesStore.addMovie({ name: 'Star Wars' });
11 |
12 | moviesStore.state$.subscribe((state) => {
13 | expect(state.movies.length).toBe(1);
14 | expect(state.movies[0]).toEqual({ id: 1, name: 'Star Wars' });
15 | done();
16 | });
17 | });
18 |
19 | it('should have the (maximum + 1) of the existing ids as id', () => {
20 | const moviesStore = new MoviesStore();
21 | moviesStore.setState({ movies: [
22 | {id: 1, name: 'Darkwing Duck'},
23 | {id: 9, name: 'Gargoyles'}
24 | ] });
25 |
26 | moviesStore.addMovie({name: 'Dragonball'});
27 |
28 | moviesStore.state$.subscribe(state => {
29 | expect(state.movies.length).toBe(3);
30 | expect(state.movies[2]).toEqual({id: 10, name: 'Dragonball'});
31 | });
32 | });
33 | });
34 |
35 | describe('deleteMovie reducer', () => {
36 | it('should remove an existing movie from the store', (done) => {
37 | const moviesStore = new MoviesStore();
38 | moviesStore.setState({ movies: [{id: 1, name: 'Zorro'}] });
39 |
40 | moviesStore.deleteMovie(1);
41 |
42 | moviesStore.state$.subscribe(state => {
43 | expect(state.movies.length).toBe(0);
44 | done();
45 | });
46 | });
47 |
48 | it('should not affect the store if the movie id does not exist', (done) => {
49 | const movies = [{id: 1, name: 'Zorro'}];
50 | const moviesStore = new MoviesStore();
51 | moviesStore.setState({ movies });
52 |
53 | moviesStore.deleteMovie(2);
54 |
55 | moviesStore.state$.subscribe(state => {
56 | expect(state.movies).toEqual(movies);
57 | done();
58 | });
59 | });
60 | });
61 |
62 | describe('movies$ selector', () => {
63 | it('should return an empty array as a default state', (done) => {
64 | const moviesStore = new MoviesStore();
65 |
66 | moviesStore.movies$.subscribe(movies => {
67 | expect(movies.length).toBe(0);
68 | done();
69 | });
70 | });
71 |
72 | it('should return the correct movies in the store', (done) => {
73 | const moviesStore = new MoviesStore();
74 | moviesStore.setState({ movies: [] });
75 | const moviesData = [
76 | { id: 1, name: 'Spiderman' },
77 | { id: 2, name: 'Star Wars' }
78 | ];
79 |
80 | moviesStore.setState({ movies: moviesData });
81 |
82 | moviesStore.movies$.subscribe(movies => {
83 | expect(movies).toEqual(moviesData);
84 | done();
85 | });
86 | });
87 | });
88 | });
89 |
--------------------------------------------------------------------------------
/src/polyfills.ts:
--------------------------------------------------------------------------------
1 | /**
2 | * This file includes polyfills needed by Angular and is loaded before the app.
3 | * You can add your own extra polyfills to this file.
4 | *
5 | * This file is divided into 2 sections:
6 | * 1. Browser polyfills. These are applied before loading ZoneJS and are sorted by browsers.
7 | * 2. Application imports. Files imported after ZoneJS that should be loaded before your main
8 | * file.
9 | *
10 | * The current setup is for so-called "evergreen" browsers; the last versions of browsers that
11 | * automatically update themselves. This includes Safari >= 10, Chrome >= 55 (including Opera),
12 | * Edge >= 13 on the desktop, and iOS 10 and Chrome on mobile.
13 | *
14 | * Learn more in https://angular.io/guide/browser-support
15 | */
16 |
17 | /***************************************************************************************************
18 | * BROWSER POLYFILLS
19 | */
20 |
21 | /** IE10 and IE11 requires the following for NgClass support on SVG elements */
22 | // import 'classlist.js'; // Run `npm install --save classlist.js`.
23 |
24 | /**
25 | * Web Animations `@angular/platform-browser/animations`
26 | * Only required if AnimationBuilder is used within the application and using IE/Edge or Safari.
27 | * Standard animation support in Angular DOES NOT require any polyfills (as of Angular 6.0).
28 | */
29 | // import 'web-animations-js'; // Run `npm install --save web-animations-js`.
30 |
31 | /**
32 | * By default, zone.js will patch all possible macroTask and DomEvents
33 | * user can disable parts of macroTask/DomEvents patch by setting following flags
34 | * because those flags need to be set before `zone.js` being loaded, and webpack
35 | * will put import in the top of bundle, so user need to create a separate file
36 | * in this directory (for example: zone-flags.ts), and put the following flags
37 | * into that file, and then add the following code before importing zone.js.
38 | * import './zone-flags';
39 | *
40 | * The flags allowed in zone-flags.ts are listed here.
41 | *
42 | * The following flags will work for all browsers.
43 | *
44 | * (window as any).__Zone_disable_requestAnimationFrame = true; // disable patch requestAnimationFrame
45 | * (window as any).__Zone_disable_on_property = true; // disable patch onProperty such as onclick
46 | * (window as any).__zone_symbol__UNPATCHED_EVENTS = ['scroll', 'mousemove']; // disable patch specified eventNames
47 | *
48 | * in IE/Edge developer tools, the addEventListener will also be wrapped by zone.js
49 | * with the following flag, it will bypass `zone.js` patch for IE/Edge
50 | *
51 | * (window as any).__Zone_enable_cross_context_check = true;
52 | *
53 | */
54 |
55 | /***************************************************************************************************
56 | * Zone JS is required by default for Angular itself.
57 | */
58 | import 'zone.js/dist/zone'; // Included with Angular CLI.
59 |
60 |
61 | /***************************************************************************************************
62 | * APPLICATION IMPORTS
63 | */
64 |
--------------------------------------------------------------------------------
/tslint.json:
--------------------------------------------------------------------------------
1 | {
2 | "extends": "tslint:recommended",
3 | "rulesDirectory": [
4 | "codelyzer"
5 | ],
6 | "rules": {
7 | "align": {
8 | "options": [
9 | "parameters",
10 | "statements"
11 | ]
12 | },
13 | "array-type": false,
14 | "arrow-return-shorthand": true,
15 | "curly": true,
16 | "deprecation": {
17 | "severity": "warning"
18 | },
19 | "eofline": true,
20 | "import-blacklist": [
21 | true,
22 | "rxjs/Rx"
23 | ],
24 | "import-spacing": true,
25 | "indent": {
26 | "options": [
27 | "spaces"
28 | ]
29 | },
30 | "max-classes-per-file": false,
31 | "max-line-length": [
32 | true,
33 | 140
34 | ],
35 | "member-ordering": [
36 | true,
37 | {
38 | "order": [
39 | "static-field",
40 | "instance-field",
41 | "static-method",
42 | "instance-method"
43 | ]
44 | }
45 | ],
46 | "no-console": [
47 | true,
48 | "debug",
49 | "info",
50 | "time",
51 | "timeEnd",
52 | "trace"
53 | ],
54 | "no-empty": false,
55 | "no-inferrable-types": [
56 | true,
57 | "ignore-params"
58 | ],
59 | "no-non-null-assertion": true,
60 | "no-redundant-jsdoc": true,
61 | "no-switch-case-fall-through": true,
62 | "no-var-requires": false,
63 | "object-literal-key-quotes": [
64 | true,
65 | "as-needed"
66 | ],
67 | "quotemark": [
68 | true,
69 | "single"
70 | ],
71 | "semicolon": {
72 | "options": [
73 | "always"
74 | ]
75 | },
76 | "space-before-function-paren": {
77 | "options": {
78 | "anonymous": "never",
79 | "asyncArrow": "always",
80 | "constructor": "never",
81 | "method": "never",
82 | "named": "never"
83 | }
84 | },
85 | "typedef": [
86 | true,
87 | "call-signature"
88 | ],
89 | "typedef-whitespace": {
90 | "options": [
91 | {
92 | "call-signature": "nospace",
93 | "index-signature": "nospace",
94 | "parameter": "nospace",
95 | "property-declaration": "nospace",
96 | "variable-declaration": "nospace"
97 | },
98 | {
99 | "call-signature": "onespace",
100 | "index-signature": "onespace",
101 | "parameter": "onespace",
102 | "property-declaration": "onespace",
103 | "variable-declaration": "onespace"
104 | }
105 | ]
106 | },
107 | "variable-name": {
108 | "options": [
109 | "ban-keywords",
110 | "check-format",
111 | "allow-pascal-case"
112 | ]
113 | },
114 | "whitespace": {
115 | "options": [
116 | "check-branch",
117 | "check-decl",
118 | "check-operator",
119 | "check-separator",
120 | "check-type",
121 | "check-typecast"
122 | ]
123 | },
124 | "component-class-suffix": true,
125 | "contextual-lifecycle": true,
126 | "directive-class-suffix": true,
127 | "no-conflicting-lifecycle": true,
128 | "no-host-metadata-property": true,
129 | "no-input-rename": true,
130 | "no-inputs-metadata-property": true,
131 | "no-output-native": true,
132 | "no-output-on-prefix": true,
133 | "no-output-rename": true,
134 | "no-outputs-metadata-property": true,
135 | "template-banana-in-box": true,
136 | "template-no-negated-async": true,
137 | "use-lifecycle-interface": true,
138 | "use-pipe-transform-interface": true,
139 | "directive-selector": [
140 | true,
141 | "attribute",
142 | "app",
143 | "camelCase"
144 | ],
145 | "component-selector": [
146 | true,
147 | "element",
148 | "app",
149 | "kebab-case"
150 | ]
151 | }
152 | }
153 |
--------------------------------------------------------------------------------
/src/app/movies/movies.component.spec.ts:
--------------------------------------------------------------------------------
1 | import { ComponentFixture, TestBed } from '@angular/core/testing';
2 | import { ReactiveFormsModule } from '@angular/forms';
3 | import { By } from '@angular/platform-browser';
4 | import { of } from 'rxjs';
5 | import { MoviesComponent } from './movies.component';
6 | import { MoviesStore } from './movies.component.store';
7 |
8 |
9 | describe('MoviesComponent', () => {
10 | let component: MoviesComponent;
11 | let fixture: ComponentFixture;
12 | const mockMoviesStore = jasmine.createSpyObj('MoviesStore', ['setState', 'addMovie'], { movies$: of([]) });
13 |
14 | beforeEach((() => {
15 | TestBed.configureTestingModule({
16 | declarations: [ MoviesComponent ],
17 | imports: [ ReactiveFormsModule ]
18 | });
19 | TestBed.overrideProvider(MoviesStore, { useValue: mockMoviesStore });
20 | fixture = TestBed.createComponent(MoviesComponent);
21 | component = fixture.componentInstance;
22 | fixture.detectChanges();
23 | }));
24 |
25 | describe('addMovies', () => {
26 | it('should reflect the DOM input value in the FormGroup', () => {
27 | const hostElement = fixture.nativeElement;
28 | const nameInput: HTMLInputElement = hostElement.querySelector('form input');
29 |
30 | nameInput.value = 'Star Wars';
31 | nameInput.dispatchEvent(new Event('input'));
32 | fixture.detectChanges();
33 |
34 | expect(fixture.componentInstance.addMovieForm.value).toEqual({ name: 'Star Wars' });
35 | });
36 |
37 | it('should dispatch the moviesStore.addMovie action with the FormGroup value', () => {
38 | fixture.componentInstance.addMovieForm.setValue({ name: 'Batman' });
39 |
40 | fixture.componentInstance.addMovie();
41 |
42 | expect(mockMoviesStore.addMovie).toHaveBeenCalledWith({ name: 'Batman' });
43 | });
44 |
45 | it('should clear the form if a movie is added', () => {
46 | fixture.componentInstance.addMovieForm.setValue({ name: 'Terminator' });
47 |
48 | fixture.componentInstance.addMovie();
49 |
50 | expect(fixture.componentInstance.addMovieForm.value).toEqual({ name: null });
51 | });
52 | });
53 |
54 | describe('deleteMovie', () => {
55 | it('should trigger the deleteMovie component store function if the user clicks the delete button', () => {
56 | const moviesData = [{id: 7, name: 'Powerrangers'}, {id: 2, name: 'Batman'}];
57 | const testMockMovieStore = jasmine.createSpyObj('MoviesStore', ['setState', 'deleteMovie'], { movies$: of(moviesData) });
58 | TestBed.overrideProvider(MoviesStore, { useValue: testMockMovieStore });
59 | fixture = TestBed.createComponent(MoviesComponent);
60 | fixture.detectChanges();
61 |
62 | const movies = fixture.debugElement.queryAll(By.css('.movie'));
63 | movies[0].query(By.css('button.delete')).triggerEventHandler('click', null);
64 |
65 | expect(testMockMovieStore.deleteMovie).toHaveBeenCalledWith(7);
66 | });
67 | });
68 |
69 | describe('movies$ selector', () => {
70 | it('should display no movies by default', () => {
71 | const movieElements = fixture.debugElement.queryAll(By.css('.movie'));
72 |
73 | expect(movieElements.length).toBe(0);
74 | });
75 |
76 | it('should be a reference to the moviesStore movies$', () => {
77 | expect(fixture.componentInstance.movies$).toBe(mockMoviesStore.movies$);
78 | });
79 |
80 | it('should display movies$ in the DOM', () => {
81 | const moviesData = [{id: 1, name: 'Powerrangers'}, {id: 2, name: 'Batman'}];
82 | const testMockMovieStore = jasmine.createSpyObj('MoviesStore', ['setState'], { movies$: of(moviesData) });
83 | TestBed.overrideProvider(MoviesStore, { useValue: testMockMovieStore });
84 | fixture = TestBed.createComponent(MoviesComponent);
85 | fixture.detectChanges();
86 |
87 | const movies = fixture.debugElement.queryAll(By.css('.movie'));
88 | expect(movies[0].nativeElement.textContent).toContain('Powerrangers');
89 | expect(movies[1].nativeElement.textContent).toContain('Batman');
90 | });
91 | });
92 | });
93 |
--------------------------------------------------------------------------------
/angular.json:
--------------------------------------------------------------------------------
1 | {
2 | "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
3 | "version": 1,
4 | "newProjectRoot": "projects",
5 | "projects": {
6 | "ngrx-component-store-testing": {
7 | "projectType": "application",
8 | "schematics": {},
9 | "root": "",
10 | "sourceRoot": "src",
11 | "prefix": "app",
12 | "architect": {
13 | "build": {
14 | "builder": "@angular-devkit/build-angular:browser",
15 | "options": {
16 | "outputPath": "dist/ngrx-component-store-testing",
17 | "index": "src/index.html",
18 | "main": "src/main.ts",
19 | "polyfills": "src/polyfills.ts",
20 | "tsConfig": "tsconfig.app.json",
21 | "aot": true,
22 | "assets": [
23 | "src/favicon.ico",
24 | "src/assets"
25 | ],
26 | "styles": [
27 | "src/styles.css"
28 | ],
29 | "scripts": []
30 | },
31 | "configurations": {
32 | "production": {
33 | "fileReplacements": [
34 | {
35 | "replace": "src/environments/environment.ts",
36 | "with": "src/environments/environment.prod.ts"
37 | }
38 | ],
39 | "optimization": true,
40 | "outputHashing": "all",
41 | "sourceMap": false,
42 | "extractCss": true,
43 | "namedChunks": false,
44 | "extractLicenses": true,
45 | "vendorChunk": false,
46 | "buildOptimizer": true,
47 | "budgets": [
48 | {
49 | "type": "initial",
50 | "maximumWarning": "2mb",
51 | "maximumError": "5mb"
52 | },
53 | {
54 | "type": "anyComponentStyle",
55 | "maximumWarning": "6kb",
56 | "maximumError": "10kb"
57 | }
58 | ]
59 | }
60 | }
61 | },
62 | "serve": {
63 | "builder": "@angular-devkit/build-angular:dev-server",
64 | "options": {
65 | "browserTarget": "ngrx-component-store-testing:build"
66 | },
67 | "configurations": {
68 | "production": {
69 | "browserTarget": "ngrx-component-store-testing:build:production"
70 | }
71 | }
72 | },
73 | "extract-i18n": {
74 | "builder": "@angular-devkit/build-angular:extract-i18n",
75 | "options": {
76 | "browserTarget": "ngrx-component-store-testing:build"
77 | }
78 | },
79 | "test": {
80 | "builder": "@angular-devkit/build-angular:karma",
81 | "options": {
82 | "main": "src/test.ts",
83 | "polyfills": "src/polyfills.ts",
84 | "tsConfig": "tsconfig.spec.json",
85 | "karmaConfig": "karma.conf.js",
86 | "assets": [
87 | "src/favicon.ico",
88 | "src/assets"
89 | ],
90 | "styles": [
91 | "src/styles.css"
92 | ],
93 | "scripts": [],
94 | "codeCoverage": true
95 | },
96 | "configurations": {
97 | "ci": {
98 | "watch": false,
99 | "progress": false,
100 | "browsers": "ChromeHeadlessCI"
101 | }
102 | }
103 | },
104 | "lint": {
105 | "builder": "@angular-devkit/build-angular:tslint",
106 | "options": {
107 | "tsConfig": [
108 | "tsconfig.app.json",
109 | "tsconfig.spec.json",
110 | "e2e/tsconfig.json"
111 | ],
112 | "exclude": [
113 | "**/node_modules/**"
114 | ]
115 | }
116 | },
117 | "e2e": {
118 | "builder": "@angular-devkit/build-angular:protractor",
119 | "options": {
120 | "protractorConfig": "e2e/protractor.conf.js",
121 | "devServerTarget": "ngrx-component-store-testing:serve"
122 | },
123 | "configurations": {
124 | "production": {
125 | "devServerTarget": "ngrx-component-store-testing:serve:production"
126 | }
127 | }
128 | }
129 | }
130 | }},
131 | "defaultProject": "ngrx-component-store-testing"
132 | }
133 |
--------------------------------------------------------------------------------