├── .angular-cli.json ├── .editorconfig ├── .gitignore ├── README.md ├── e2e ├── app.e2e-spec.ts ├── app.po.ts └── tsconfig.e2e.json ├── jest.config.js ├── package-lock.json ├── package.json ├── protractor.conf.js ├── src ├── app │ ├── __snapshots__ │ │ └── app.component.spec.ts.snap │ ├── app.component.css │ ├── app.component.html │ ├── app.component.spec.ts │ ├── app.component.ts │ ├── app.module.ts │ ├── app.routing.module.ts │ ├── core │ │ ├── core.module.ts │ │ ├── in-memory-data.service.ts │ │ └── services │ │ │ └── customer.service.ts │ ├── customers │ │ ├── components │ │ │ └── customers │ │ │ │ ├── __snapshots__ │ │ │ │ └── customers.component.spec.ts.snap │ │ │ │ ├── customers.component.css │ │ │ │ ├── customers.component.html │ │ │ │ ├── customers.component.spec.ts │ │ │ │ └── customers.component.ts │ │ ├── containers │ │ │ └── customers │ │ │ │ ├── __snapshots__ │ │ │ │ └── customers.component.spec.ts.snap │ │ │ │ ├── customers.component.css │ │ │ │ ├── customers.component.html │ │ │ │ ├── customers.component.spec.ts │ │ │ │ └── customers.component.ts │ │ ├── customers.module.ts │ │ └── customers.routing.module.ts │ └── state │ │ ├── app.interfaces.ts │ │ ├── app.reducer.ts │ │ ├── customer │ │ ├── __snapshots__ │ │ │ ├── customer.actions.spec.ts.snap │ │ │ ├── customer.effects.spec.ts.snap │ │ │ └── customer.reducer.spec.ts.snap │ │ ├── customer.actions.spec.ts │ │ ├── customer.actions.ts │ │ ├── customer.effects.spec.ts │ │ ├── customer.effects.ts │ │ ├── customer.model.ts │ │ ├── customer.reducer.spec.ts │ │ ├── customer.reducer.ts │ │ └── index.ts │ │ ├── shared │ │ └── utils.ts │ │ └── state.module.ts ├── assets │ └── .gitkeep ├── environments │ ├── environment.prod.ts │ └── environment.ts ├── favicon.ico ├── index.html ├── main.ts ├── polyfills.ts ├── setup-jest.ts ├── styles.css ├── sum.spec.ts ├── sum.ts ├── test-config.helper.ts ├── tsconfig.app.json ├── tsconfig.spec.json └── typings.d.ts ├── tsconfig.json ├── tslint.json └── yarn.lock /.angular-cli.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "./node_modules/@angular/cli/lib/config/schema.json", 3 | "project": { 4 | "name": "ngrx-jest-testing" 5 | }, 6 | "apps": [ 7 | { 8 | "root": "src", 9 | "outDir": "dist", 10 | "assets": [ 11 | "assets", 12 | "favicon.ico" 13 | ], 14 | "index": "index.html", 15 | "main": "main.ts", 16 | "polyfills": "polyfills.ts", 17 | "test": "test.ts", 18 | "tsconfig": "tsconfig.app.json", 19 | "testTsconfig": "tsconfig.spec.json", 20 | "prefix": "app", 21 | "styles": [ 22 | "styles.css" 23 | ], 24 | "scripts": [], 25 | "environmentSource": "environments/environment.ts", 26 | "environments": { 27 | "dev": "environments/environment.ts", 28 | "prod": "environments/environment.prod.ts" 29 | } 30 | } 31 | ], 32 | "e2e": { 33 | "protractor": { 34 | "config": "./protractor.conf.js" 35 | } 36 | }, 37 | "lint": [ 38 | { 39 | "project": "src/tsconfig.app.json", 40 | "exclude": "**/node_modules/**" 41 | }, 42 | { 43 | "project": "src/tsconfig.spec.json", 44 | "exclude": "**/node_modules/**" 45 | }, 46 | { 47 | "project": "e2e/tsconfig.e2e.json", 48 | "exclude": "**/node_modules/**" 49 | } 50 | ], 51 | "test": { 52 | "karma": { 53 | "config": "./karma.conf.js" 54 | } 55 | }, 56 | "defaults": { 57 | "styleExt": "css", 58 | "component": {} 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | # Editor configuration, see http://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 | quote_type = single 11 | 12 | [*.md] 13 | max_line_length = off 14 | trim_trailing_whitespace = false 15 | -------------------------------------------------------------------------------- /.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 | 8 | # dependencies 9 | /node_modules 10 | 11 | # IDEs and editors 12 | /.idea 13 | .project 14 | .classpath 15 | .c9/ 16 | *.launch 17 | .settings/ 18 | *.sublime-workspace 19 | 20 | # IDE - VSCode 21 | .vscode/* 22 | !.vscode/settings.json 23 | !.vscode/tasks.json 24 | !.vscode/launch.json 25 | !.vscode/extensions.json 26 | 27 | # misc 28 | /.sass-cache 29 | /connect.lock 30 | /coverage 31 | /libpeerconnection.log 32 | npm-debug.log 33 | testem.log 34 | /typings 35 | 36 | # e2e 37 | /e2e/*.js 38 | /e2e/*.map 39 | 40 | # System Files 41 | .DS_Store 42 | Thumbs.db 43 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # NgrxJestTesting 2 | 3 | This project was generated with [Angular CLI](https://github.com/angular/angular-cli) version 1.6.1. 4 | 5 | ## Development server 6 | 7 | Run `ng serve` for a dev server. Navigate to `http://localhost:4200/`. The app will automatically reload if you change any of the source files. 8 | 9 | ## Code scaffolding 10 | 11 | Run `ng generate component component-name` to generate a new component. You can also use `ng generate directive|pipe|service|class|guard|interface|enum|module`. 12 | 13 | ## Build 14 | 15 | Run `ng build` to build the project. The build artifacts will be stored in the `dist/` directory. Use the `-prod` flag for a production build. 16 | 17 | ## Running unit tests 18 | 19 | Run `ng test` to execute the unit tests via [Karma](https://karma-runner.github.io). 20 | 21 | ## Running end-to-end tests 22 | 23 | Run `ng e2e` to execute the end-to-end tests via [Protractor](http://www.protractortest.org/). 24 | 25 | ## Further help 26 | 27 | To get more help on the Angular CLI use `ng help` or go check out the [Angular CLI README](https://github.com/angular/angular-cli/blob/master/README.md). 28 | -------------------------------------------------------------------------------- /e2e/app.e2e-spec.ts: -------------------------------------------------------------------------------- 1 | import { AppPage } from './app.po'; 2 | 3 | describe('ngrx-jest-testing App', () => { 4 | let page: AppPage; 5 | 6 | beforeEach(() => { 7 | page = new AppPage(); 8 | }); 9 | 10 | it('should display welcome message', () => { 11 | page.navigateTo(); 12 | expect(page.getParagraphText()).toEqual('Welcome to app!'); 13 | }); 14 | }); 15 | -------------------------------------------------------------------------------- /e2e/app.po.ts: -------------------------------------------------------------------------------- 1 | import { browser, by, element } from 'protractor'; 2 | 3 | export class AppPage { 4 | navigateTo() { 5 | return browser.get('/'); 6 | } 7 | 8 | getParagraphText() { 9 | return element(by.css('app-root h1')).getText(); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /e2e/tsconfig.e2e.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "../tsconfig.json", 3 | "compilerOptions": { 4 | "outDir": "../out-tsc/e2e", 5 | "baseUrl": "./", 6 | "module": "commonjs", 7 | "target": "es5", 8 | "types": [ 9 | "jasmine", 10 | "jasminewd2", 11 | "node" 12 | ] 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /jest.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | preset: 'jest-preset-angular', 3 | roots: ['src'], 4 | setupTestFrameworkScriptFile: '/src/setup-jest.ts', 5 | moduleNameMapper: { 6 | '@app/(.*)': '/src/app/$1', 7 | '@assets/(.*)': '/src/assets/$1', 8 | '@core/(.*)': '/src/app/core/$1', 9 | '@env': '/src/environments/environment', 10 | '@src/(.*)': '/src/src/$1', 11 | '@state/(.*)': '/src/app/state/$1' 12 | } 13 | }; 14 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "ngrx-jest-testing", 3 | "version": "0.0.0", 4 | "license": "MIT", 5 | "scripts": { 6 | "ng": "ng", 7 | "start": "ng serve", 8 | "build": "ng build --prod", 9 | "test": "jest", 10 | "lint": "ng lint", 11 | "e2e": "ng e2e" 12 | }, 13 | "private": true, 14 | "dependencies": { 15 | "@angular/animations": "^5.0.0", 16 | "@angular/common": "^5.0.0", 17 | "@angular/compiler": "^5.0.0", 18 | "@angular/core": "^5.0.0", 19 | "@angular/forms": "^5.0.0", 20 | "@angular/http": "^5.0.0", 21 | "@angular/platform-browser": "^5.0.0", 22 | "@angular/platform-browser-dynamic": "^5.0.0", 23 | "@angular/router": "^5.0.0", 24 | "@ngrx/effects": "^5.0.1", 25 | "@ngrx/entity": "^5.0.1", 26 | "@ngrx/store": "^5.0.0", 27 | "@ngrx/store-devtools": "^5.0.1", 28 | "angular-in-memory-web-api": "^0.5.4", 29 | "core-js": "^2.4.1", 30 | "rxjs": "^5.5.2", 31 | "zone.js": "^0.8.14" 32 | }, 33 | "devDependencies": { 34 | "@angular/cli": "^1.6.8", 35 | "@angular/compiler-cli": "^5.0.0", 36 | "@angular/language-service": "^5.0.0", 37 | "@ngrx/router-store": "^5.2.0", 38 | "@types/node": "~6.0.60", 39 | "codelyzer": "^4.0.1", 40 | "jasmine-marbles": "^0.2.0", 41 | "jest": "^22.4.4", 42 | "jest-preset-angular": "^5.0.0", 43 | "ngrx-store-freeze": "^0.2.1", 44 | "protractor": "~5.1.2", 45 | "ts-node": "~3.2.0", 46 | "tslint": "~5.7.0", 47 | "typescript": "~2.4.2" 48 | }, 49 | "prettier": { 50 | "singleQuote": true 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /protractor.conf.js: -------------------------------------------------------------------------------- 1 | // Protractor configuration file, see link for more information 2 | // https://github.com/angular/protractor/blob/master/lib/config.ts 3 | 4 | const { SpecReporter } = require('jasmine-spec-reporter'); 5 | 6 | exports.config = { 7 | allScriptsTimeout: 11000, 8 | specs: [ 9 | './e2e/**/*.e2e-spec.ts' 10 | ], 11 | capabilities: { 12 | 'browserName': 'chrome' 13 | }, 14 | directConnect: true, 15 | baseUrl: 'http://localhost:4200/', 16 | framework: 'jasmine', 17 | jasmineNodeOpts: { 18 | showColors: true, 19 | defaultTimeoutInterval: 30000, 20 | print: function() {} 21 | }, 22 | onPrepare() { 23 | require('ts-node').register({ 24 | project: 'e2e/tsconfig.e2e.json' 25 | }); 26 | jasmine.getEnv().addReporter(new SpecReporter({ spec: { displayStacktrace: true } })); 27 | } 28 | }; 29 | -------------------------------------------------------------------------------- /src/app/__snapshots__/app.component.spec.ts.snap: -------------------------------------------------------------------------------- 1 | // Jest Snapshot v1, https://goo.gl/fbAQLP 2 | 3 | exports[`AppComponent should render html 1`] = ` 4 |
8 | 9 |
10 | `; 11 | -------------------------------------------------------------------------------- /src/app/app.component.css: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/briebug/ngrx-jest-testing/6e855232c4d59ec4694157415a3ce8b23eacc2f3/src/app/app.component.css -------------------------------------------------------------------------------- /src/app/app.component.html: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /src/app/app.component.spec.ts: -------------------------------------------------------------------------------- 1 | import { TestBed, ComponentFixture, async } from '@angular/core/testing'; 2 | import { RouterTestingModule } from '@angular/router/testing'; 3 | import { configureTests, ConfigureFn } from '../test-config.helper' 4 | import { AppComponent } from './app.component'; 5 | 6 | describe('AppComponent', () => { 7 | let fixture: ComponentFixture, 8 | app: AppComponent; 9 | 10 | beforeEach( 11 | async(() => { 12 | const configure: ConfigureFn = testBed => { 13 | testBed.configureTestingModule({ 14 | declarations: [AppComponent], 15 | imports: [RouterTestingModule] 16 | }); 17 | }; 18 | 19 | configureTests(configure).then(testBed => { 20 | fixture = testBed.createComponent(AppComponent); 21 | app = fixture.componentInstance; 22 | fixture.detectChanges(); 23 | }); 24 | }) 25 | ); 26 | 27 | it('should create the app', async(() => { 28 | expect(app).toBeTruthy(); 29 | })); 30 | 31 | it('should render html', async(() => { 32 | const compiled = fixture.debugElement.nativeElement; 33 | expect(compiled).toMatchSnapshot(); 34 | })); 35 | }); 36 | -------------------------------------------------------------------------------- /src/app/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 | } 11 | -------------------------------------------------------------------------------- /src/app/app.module.ts: -------------------------------------------------------------------------------- 1 | import { BrowserModule } from '@angular/platform-browser'; 2 | import { NgModule } from '@angular/core'; 3 | 4 | import { AppRoutingModule } from './app.routing.module'; 5 | import { AppComponent } from './app.component'; 6 | import { StateModule } from './state/state.module'; 7 | import { CoreModule } from './core/core.module'; 8 | import { HttpClientModule } from '@angular/common/http'; 9 | import { InMemoryWebApiModule } from 'angular-in-memory-web-api'; 10 | import { InMemoryDataService } from '@core/in-memory-data.service'; 11 | 12 | @NgModule({ 13 | declarations: [AppComponent], 14 | imports: [ 15 | BrowserModule, 16 | AppRoutingModule, 17 | HttpClientModule, 18 | StateModule.forRoot(), 19 | CoreModule.forRoot(), 20 | InMemoryWebApiModule.forRoot(InMemoryDataService, { delay: 600 }) 21 | ], 22 | bootstrap: [AppComponent] 23 | }) 24 | export class AppModule { } 25 | -------------------------------------------------------------------------------- /src/app/app.routing.module.ts: -------------------------------------------------------------------------------- 1 | import { NgModule } from '@angular/core'; 2 | import { RouterModule, Routes } from '@angular/router'; 3 | 4 | import { CustomersRoutingModule } from './customers/customers.routing.module'; 5 | 6 | const routes: Routes = [ 7 | { 8 | path: '', 9 | redirectTo: '/customers', 10 | pathMatch: 'full' 11 | }, 12 | { 13 | path: 'customers', 14 | loadChildren: 'app/customers/customers.routing.module#CustomersRoutingModule' 15 | } 16 | ]; 17 | 18 | @NgModule({ 19 | imports: [RouterModule.forRoot(routes)], 20 | exports: [RouterModule] 21 | }) 22 | export class AppRoutingModule { } 23 | -------------------------------------------------------------------------------- /src/app/core/core.module.ts: -------------------------------------------------------------------------------- 1 | import { CommonModule } from '@angular/common'; 2 | import { 3 | ModuleWithProviders, 4 | NgModule, 5 | Optional, 6 | SkipSelf 7 | } from '@angular/core'; 8 | 9 | import { CustomersService } from '@core/services/customer.service'; 10 | 11 | @NgModule({ 12 | imports: [CommonModule], 13 | providers: [CustomersService] 14 | }) 15 | export class CoreModule { 16 | static forRoot(): ModuleWithProviders { 17 | return { 18 | ngModule: CoreModule 19 | }; 20 | } 21 | 22 | constructor( 23 | @Optional() 24 | @SkipSelf() 25 | parentModule: CoreModule 26 | ) { 27 | if (parentModule) { 28 | throw new Error( 29 | 'CoreModule is already loaded. Import it in the AppModule only' 30 | ); 31 | } 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/app/core/in-memory-data.service.ts: -------------------------------------------------------------------------------- 1 | import { Customer } from '@state/customer/customer.model'; 2 | 3 | export class InMemoryDataService { 4 | createDb() { 5 | const customers = [ 6 | { id: 1, name: 'Bob Newman' } as Customer, 7 | { id: 2, name: 'Homer Simpson' } as Customer, 8 | { id: 3, name: 'Tom Slick' } as Customer, 9 | { id: 4, name: 'Jane Doe' } as Customer 10 | ]; 11 | 12 | return { customers }; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/app/core/services/customer.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | import { HttpClient } from '@angular/common/http'; 3 | import { Observable } from 'rxjs/Observable'; 4 | import { map } from 'rxjs/operators'; 5 | import { Customer } from '@state/customer/customer.model'; 6 | 7 | @Injectable() 8 | export class CustomersService { 9 | private API_PATH = '/api/customers'; 10 | 11 | constructor(private http: HttpClient) { } 12 | 13 | load(): Observable { 14 | return this.http.get(this.API_PATH); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/app/customers/components/customers/__snapshots__/customers.component.spec.ts.snap: -------------------------------------------------------------------------------- 1 | // Jest Snapshot v1, https://goo.gl/fbAQLP 2 | 3 | exports[`CustomersComponent renders customers markup to snapshot 1`] = ` 4 | 7 |
    8 | 9 |
  • 10 | Customer: 1 - test1 11 |
  • 12 |
  • 13 | Customer: 2 - test2 14 |
  • 15 |
  • 16 | Customer: 3 - test3 17 |
  • 18 |
19 |
20 | `; 21 | -------------------------------------------------------------------------------- /src/app/customers/components/customers/customers.component.css: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/briebug/ngrx-jest-testing/6e855232c4d59ec4694157415a3ce8b23eacc2f3/src/app/customers/components/customers/customers.component.css -------------------------------------------------------------------------------- /src/app/customers/components/customers/customers.component.html: -------------------------------------------------------------------------------- 1 |
    2 |
  • Customer: {{customer.id}} - {{customer.name}} 3 |
  • 4 |
5 | -------------------------------------------------------------------------------- /src/app/customers/components/customers/customers.component.spec.ts: -------------------------------------------------------------------------------- 1 | import { async, ComponentFixture, TestBed } from '@angular/core/testing'; 2 | import { Store } from '@ngrx/store'; 3 | import { hot } from 'jasmine-marbles'; 4 | import { configureTests, ConfigureFn } from '../../../../test-config.helper' 5 | import { Customer } from '@state/customer/customer.model'; 6 | import { CustomersComponent } from './customers.component'; 7 | 8 | describe('CustomersComponent', () => { 9 | let component: CustomersComponent, 10 | fixture: ComponentFixture, 11 | customers = [ 12 | { id: 1, name: 'test1' }, 13 | { id: 2, name: 'test2' }, 14 | { id: 3, name: 'test3' } 15 | ]; 16 | 17 | beforeEach( 18 | async(() => { 19 | const configure: ConfigureFn = testBed => { 20 | testBed.configureTestingModule({ 21 | declarations: [CustomersComponent], 22 | providers: [ 23 | { 24 | provide: Store, 25 | useValue: { 26 | dispatch: jest.fn(), 27 | pipe: jest.fn(() => hot('-a', { a: customers })) 28 | } 29 | } 30 | ] 31 | }); 32 | }; 33 | 34 | configureTests(configure).then(testBed => { 35 | fixture = testBed.createComponent(CustomersComponent); 36 | component = fixture.componentInstance; 37 | fixture.detectChanges(); 38 | }); 39 | }) 40 | ); 41 | 42 | test('should create', () => { 43 | expect(component).toBeTruthy(); 44 | }); 45 | 46 | test('renders customers markup to snapshot', () => { 47 | component.customers = customers; 48 | fixture.detectChanges(); 49 | 50 | expect(fixture).toMatchSnapshot(); 51 | }); 52 | }); 53 | -------------------------------------------------------------------------------- /src/app/customers/components/customers/customers.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit, Input } from '@angular/core'; 2 | import { CustomerActions } from '@state/customer/customer.actions'; 3 | import { Customer } from '@state/customer/customer.model'; 4 | 5 | @Component({ 6 | selector: 'app-customers', 7 | templateUrl: './customers.component.html', 8 | styleUrls: ['./customers.component.css'] 9 | }) 10 | export class CustomersComponent implements OnInit { 11 | @Input() customers: Customer[]; 12 | 13 | constructor() { } 14 | 15 | ngOnInit() { } 16 | } 17 | -------------------------------------------------------------------------------- /src/app/customers/containers/customers/__snapshots__/customers.component.spec.ts.snap: -------------------------------------------------------------------------------- 1 | // Jest Snapshot v1, https://goo.gl/fbAQLP 2 | 3 | exports[`CustomersComponentContainer renders markup to snapshot 1`] = ` 4 | 8 |

9 | Customers 10 |

11 |
    12 | 13 |
14 |
15 |
16 | `; 17 | -------------------------------------------------------------------------------- /src/app/customers/containers/customers/customers.component.css: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/briebug/ngrx-jest-testing/6e855232c4d59ec4694157415a3ce8b23eacc2f3/src/app/customers/containers/customers/customers.component.css -------------------------------------------------------------------------------- /src/app/customers/containers/customers/customers.component.html: -------------------------------------------------------------------------------- 1 |

Customers

2 | 3 | -------------------------------------------------------------------------------- /src/app/customers/containers/customers/customers.component.spec.ts: -------------------------------------------------------------------------------- 1 | import { async, ComponentFixture, TestBed } from '@angular/core/testing'; 2 | import { Store } from '@ngrx/store'; 3 | import { hot } from 'jasmine-marbles'; 4 | import { of } from 'rxjs/observable/of'; 5 | import { configureTests, ConfigureFn } from '../../../../test-config.helper' 6 | import { CustomersComponentContainer } from './customers.component'; 7 | import { CustomersComponent } from '../../components/customers/customers.component'; 8 | 9 | describe('CustomersComponentContainer', () => { 10 | let component: CustomersComponentContainer, 11 | fixture: ComponentFixture, 12 | customers = [ 13 | { id: 1, name: 'test1' }, 14 | { id: 2, name: 'test2' }, 15 | { id: 3, name: 'test3' } 16 | ]; 17 | 18 | beforeEach( 19 | async(() => { 20 | const configure: ConfigureFn = testBed => { 21 | testBed.configureTestingModule({ 22 | declarations: [ 23 | CustomersComponentContainer, 24 | CustomersComponent 25 | ], 26 | providers: [ 27 | { 28 | provide: Store, 29 | useValue: { 30 | dispatch: jest.fn(), 31 | pipe: jest.fn(() => hot('-a', { a: customers })) 32 | } 33 | } 34 | ] 35 | }); 36 | }; 37 | 38 | configureTests(configure).then(testBed => { 39 | fixture = testBed.createComponent(CustomersComponentContainer); 40 | component = fixture.componentInstance; 41 | fixture.detectChanges(); 42 | }); 43 | }) 44 | ); 45 | 46 | test('should create', () => { 47 | expect(component).toBeTruthy(); 48 | }); 49 | 50 | test('renders markup to snapshot', () => { 51 | fixture.detectChanges(); 52 | 53 | expect(fixture).toMatchSnapshot(); 54 | }); 55 | }); 56 | -------------------------------------------------------------------------------- /src/app/customers/containers/customers/customers.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit } from '@angular/core'; 2 | import { Store, select } from '@ngrx/store'; 3 | import { AppState } from '@state/app.interfaces'; 4 | import { getAllCustomers } from '@state/customer'; 5 | import { Load } from '@state/customer/customer.actions'; 6 | import { Customer } from '@state/customer/customer.model'; 7 | import { Observable } from 'rxjs/Observable'; 8 | 9 | @Component({ 10 | selector: 'app-customers-container', 11 | templateUrl: './customers.component.html', 12 | styleUrls: ['./customers.component.css'] 13 | }) 14 | export class CustomersComponentContainer implements OnInit { 15 | customers$: Observable; 16 | 17 | constructor(private store: Store) { 18 | this.store.dispatch(new Load()); 19 | } 20 | 21 | ngOnInit() { 22 | this.customers$ = this.store.pipe(select(getAllCustomers)); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/app/customers/customers.module.ts: -------------------------------------------------------------------------------- 1 | import { CommonModule } from '@angular/common'; 2 | import { ModuleWithProviders, NgModule, Optional, SkipSelf } from '@angular/core'; 3 | 4 | import { CustomersComponentContainer } from './containers/customers/customers.component'; 5 | import { CustomersComponent } from './components/customers/customers.component'; 6 | 7 | @NgModule({ 8 | imports: [ 9 | CommonModule 10 | ], 11 | declarations: [ 12 | CustomersComponentContainer, 13 | CustomersComponent 14 | ] 15 | }) 16 | 17 | export class CustomersModule { 18 | 19 | static forRoot(): ModuleWithProviders { 20 | return { 21 | ngModule: CustomersModule, 22 | providers: [ 23 | ] 24 | }; 25 | } 26 | 27 | constructor(@Optional() @SkipSelf() parentModule: CustomersModule) { 28 | if (parentModule) { 29 | throw new Error( 30 | 'CustomersModule is already loaded. Import it in the AppModule only'); 31 | } 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/app/customers/customers.routing.module.ts: -------------------------------------------------------------------------------- 1 | import { NgModule } from '@angular/core'; 2 | import { RouterModule, Routes } from '@angular/router'; 3 | 4 | import { CustomersModule } from './customers.module'; 5 | import { CustomersComponentContainer } from './containers/customers/customers.component'; 6 | 7 | const routes: Routes = [ 8 | { 9 | path: '', 10 | component: CustomersComponentContainer 11 | } 12 | ]; 13 | 14 | @NgModule({ 15 | imports: [CustomersModule.forRoot(), RouterModule.forChild(routes)], 16 | exports: [RouterModule] 17 | }) 18 | export class CustomersRoutingModule { } 19 | -------------------------------------------------------------------------------- /src/app/state/app.interfaces.ts: -------------------------------------------------------------------------------- 1 | import { RouterReducerState } from '@ngrx/router-store'; 2 | import { RouterStateUrl } from './shared/utils'; 3 | import { State as customerState } from '@state/customer/customer.reducer'; 4 | 5 | export interface AppState { 6 | router: RouterReducerState; 7 | customer: customerState; 8 | } 9 | 10 | export type State = AppState; 11 | -------------------------------------------------------------------------------- /src/app/state/app.reducer.ts: -------------------------------------------------------------------------------- 1 | import { routerReducer } from '@ngrx/router-store'; 2 | import { ActionReducerMap, MetaReducer } from '@ngrx/store'; 3 | import { storeFreeze } from 'ngrx-store-freeze'; 4 | import { environment } from 'environments/environment'; 5 | import { AppState } from './app.interfaces'; 6 | import { reducer as customerReducer } from '@state/customer/customer.reducer'; 7 | 8 | export const appReducer: ActionReducerMap = { 9 | router: routerReducer, 10 | customer: customerReducer 11 | }; 12 | 13 | export const appMetaReducers: MetaReducer[] = !environment.production 14 | ? [storeFreeze] 15 | : []; 16 | -------------------------------------------------------------------------------- /src/app/state/customer/__snapshots__/customer.actions.spec.ts.snap: -------------------------------------------------------------------------------- 1 | // Jest Snapshot v1, https://goo.gl/fbAQLP 2 | 3 | exports[`Customer Actions Customer Select should set customer to payload in snapshot 1`] = ` 4 | Object { 5 | "id": 1, 6 | "name": "Test User", 7 | } 8 | `; 9 | 10 | exports[`Customer Actions Customer Select should set payload to customer 1`] = `"[Customer] Select"`; 11 | 12 | exports[`Customer Actions Customer Select should set payload to customer 2`] = ` 13 | Object { 14 | "id": 1, 15 | "name": "Test User", 16 | } 17 | `; 18 | 19 | exports[`Customer Actions Load Customers Success should create Customer Load Fail Action 1`] = `"[Customer] Load Fail"`; 20 | 21 | exports[`Customer Actions Load Customers Success should create Customer Load Fail Action 2`] = ` 22 | Object { 23 | "error": "Error loading customer", 24 | "status": 1, 25 | } 26 | `; 27 | 28 | exports[`Customer Actions Load Customers Success should create Customer Load Success Action 1`] = `"[Customer] Load Success"`; 29 | 30 | exports[`Customer Actions Load Customers Success should create Customer Load Success Action 2`] = ` 31 | Array [ 32 | Object { 33 | "id": 1, 34 | "name": "Test User", 35 | }, 36 | ] 37 | `; 38 | 39 | exports[`Customer Actions Load Customers should create Customer Load Action 1`] = `"[Customer] Load"`; 40 | -------------------------------------------------------------------------------- /src/app/state/customer/__snapshots__/customer.effects.spec.ts.snap: -------------------------------------------------------------------------------- 1 | // Jest Snapshot v1, https://goo.gl/fbAQLP 2 | 3 | exports[`CustomerEffects load$ should return a new customer.LoadError, on fail 1`] = ` 4 | Actions { 5 | "_isScalar": false, 6 | "operator": SwitchMapOperator { 7 | "project": [Function], 8 | "resultSelector": undefined, 9 | }, 10 | "source": Actions { 11 | "_isScalar": false, 12 | "operator": FilterOperator { 13 | "predicate": [Function], 14 | "thisArg": undefined, 15 | }, 16 | "source": TestActions { 17 | "_isScalar": false, 18 | "source": TestHotObservable { 19 | "_isScalar": false, 20 | "error": undefined, 21 | "marbles": "-a", 22 | "source": SubscriptionLoggable { 23 | "_isScalar": false, 24 | "closed": false, 25 | "hasError": false, 26 | "isStopped": false, 27 | "messages": Array [ 28 | Object { 29 | "frame": 10, 30 | "notification": Notification { 31 | "error": undefined, 32 | "hasValue": true, 33 | "kind": "N", 34 | "value": Load { 35 | "type": "[Customer] Load", 36 | }, 37 | }, 38 | }, 39 | ], 40 | "observers": Array [], 41 | "scheduler": TestScheduler { 42 | "SchedulerAction": [Function], 43 | "actions": Array [], 44 | "active": false, 45 | "assertDeepEqual": [Function], 46 | "coldObservables": Array [ 47 | SubscriptionLoggable { 48 | "_isScalar": false, 49 | "_subscribe": [Function], 50 | "messages": Array [ 51 | Object { 52 | "frame": 0, 53 | "notification": Notification { 54 | "error": "error", 55 | "hasValue": false, 56 | "kind": "E", 57 | "value": undefined, 58 | }, 59 | }, 60 | ], 61 | "scheduler": [Circular], 62 | "subscriptions": Array [], 63 | }, 64 | SubscriptionLoggable { 65 | "_isScalar": false, 66 | "_subscribe": [Function], 67 | "messages": Array [ 68 | Object { 69 | "frame": 10, 70 | "notification": Notification { 71 | "error": undefined, 72 | "hasValue": true, 73 | "kind": "N", 74 | "value": LoadFail { 75 | "error": "error", 76 | "type": "[Customer] Load Fail", 77 | }, 78 | }, 79 | }, 80 | ], 81 | "scheduler": [Circular], 82 | "subscriptions": Array [], 83 | }, 84 | ], 85 | "flushTests": Array [], 86 | "frame": 0, 87 | "hotObservables": Array [ 88 | [Circular], 89 | ], 90 | "index": -1, 91 | "maxFrames": 750, 92 | "now": [Function], 93 | "scheduled": undefined, 94 | }, 95 | "subscriptions": Array [], 96 | "thrownError": null, 97 | }, 98 | "values": Object { 99 | "a": Load { 100 | "type": "[Customer] Load", 101 | }, 102 | }, 103 | }, 104 | }, 105 | }, 106 | } 107 | `; 108 | 109 | exports[`CustomerEffects load$ should return a new customer.LoadSuccess, with the customers, on success 1`] = ` 110 | Actions { 111 | "_isScalar": false, 112 | "operator": SwitchMapOperator { 113 | "project": [Function], 114 | "resultSelector": undefined, 115 | }, 116 | "source": Actions { 117 | "_isScalar": false, 118 | "operator": FilterOperator { 119 | "predicate": [Function], 120 | "thisArg": undefined, 121 | }, 122 | "source": TestActions { 123 | "_isScalar": false, 124 | "source": TestHotObservable { 125 | "_isScalar": false, 126 | "error": undefined, 127 | "marbles": "-a", 128 | "source": SubscriptionLoggable { 129 | "_isScalar": false, 130 | "closed": false, 131 | "hasError": false, 132 | "isStopped": false, 133 | "messages": Array [ 134 | Object { 135 | "frame": 10, 136 | "notification": Notification { 137 | "error": undefined, 138 | "hasValue": true, 139 | "kind": "N", 140 | "value": Load { 141 | "type": "[Customer] Load", 142 | }, 143 | }, 144 | }, 145 | ], 146 | "observers": Array [], 147 | "scheduler": TestScheduler { 148 | "SchedulerAction": [Function], 149 | "actions": Array [], 150 | "active": false, 151 | "assertDeepEqual": [Function], 152 | "coldObservables": Array [ 153 | SubscriptionLoggable { 154 | "_isScalar": false, 155 | "_subscribe": [Function], 156 | "messages": Array [ 157 | Object { 158 | "frame": 0, 159 | "notification": Notification { 160 | "error": undefined, 161 | "hasValue": true, 162 | "kind": "N", 163 | "value": Array [ 164 | Object { 165 | "id": 1, 166 | "name": "User 1", 167 | }, 168 | Object { 169 | "id": 2, 170 | "name": "User 2", 171 | }, 172 | ], 173 | }, 174 | }, 175 | Object { 176 | "frame": 10, 177 | "notification": Notification { 178 | "error": undefined, 179 | "hasValue": false, 180 | "kind": "C", 181 | "value": undefined, 182 | }, 183 | }, 184 | ], 185 | "scheduler": [Circular], 186 | "subscriptions": Array [], 187 | }, 188 | SubscriptionLoggable { 189 | "_isScalar": false, 190 | "_subscribe": [Function], 191 | "messages": Array [ 192 | Object { 193 | "frame": 10, 194 | "notification": Notification { 195 | "error": undefined, 196 | "hasValue": true, 197 | "kind": "N", 198 | "value": LoadSuccess { 199 | "payload": Array [ 200 | Object { 201 | "id": 1, 202 | "name": "User 1", 203 | }, 204 | Object { 205 | "id": 2, 206 | "name": "User 2", 207 | }, 208 | ], 209 | "type": "[Customer] Load Success", 210 | }, 211 | }, 212 | }, 213 | ], 214 | "scheduler": [Circular], 215 | "subscriptions": Array [], 216 | }, 217 | ], 218 | "flushTests": Array [], 219 | "frame": 0, 220 | "hotObservables": Array [ 221 | [Circular], 222 | ], 223 | "index": -1, 224 | "maxFrames": 750, 225 | "now": [Function], 226 | "scheduled": undefined, 227 | }, 228 | "subscriptions": Array [], 229 | "thrownError": null, 230 | }, 231 | "values": Object { 232 | "a": Load { 233 | "type": "[Customer] Load", 234 | }, 235 | }, 236 | }, 237 | }, 238 | }, 239 | } 240 | `; 241 | -------------------------------------------------------------------------------- /src/app/state/customer/__snapshots__/customer.reducer.spec.ts.snap: -------------------------------------------------------------------------------- 1 | // Jest Snapshot v1, https://goo.gl/fbAQLP 2 | 3 | exports[`CustomersReducer Customer Select Action should set selectedCustomerId 1`] = ` 4 | Object { 5 | "entities": Object {}, 6 | "error": null, 7 | "ids": Array [], 8 | "loading": false, 9 | "selectedCustomerId": 1, 10 | } 11 | `; 12 | 13 | exports[`CustomersReducer GetSelectedCustomer selector should select customer 1`] = ` 14 | Object { 15 | "id": 1, 16 | "name": "test1", 17 | } 18 | `; 19 | 20 | exports[`CustomersReducer Load Customers Action should set loading to true 1`] = ` 21 | Object { 22 | "entities": Object {}, 23 | "error": null, 24 | "ids": Array [], 25 | "loading": true, 26 | "selectedCustomerId": null, 27 | } 28 | `; 29 | 30 | exports[`CustomersReducer Load Customers Fail Action should add error to state 1`] = ` 31 | Object { 32 | "entities": Object {}, 33 | "error": "Error loading customers", 34 | "ids": Array [], 35 | "loading": false, 36 | "selectedCustomerId": null, 37 | } 38 | `; 39 | 40 | exports[`CustomersReducer Load Customers Success Action should add customers to state 1`] = ` 41 | Object { 42 | "entities": Object { 43 | "1": Object { 44 | "id": 1, 45 | "name": "test1", 46 | }, 47 | "2": Object { 48 | "id": 2, 49 | "name": "test2", 50 | }, 51 | "3": Object { 52 | "id": 3, 53 | "name": "test3", 54 | }, 55 | }, 56 | "error": null, 57 | "ids": Array [ 58 | 1, 59 | 2, 60 | 3, 61 | ], 62 | "loading": false, 63 | "selectedCustomerId": null, 64 | } 65 | `; 66 | 67 | exports[`CustomersReducer undefined action should return the default state 1`] = ` 68 | Object { 69 | "entities": Object {}, 70 | "error": null, 71 | "ids": Array [], 72 | "loading": false, 73 | "selectedCustomerId": null, 74 | } 75 | `; 76 | -------------------------------------------------------------------------------- /src/app/state/customer/customer.actions.spec.ts: -------------------------------------------------------------------------------- 1 | import * as CustomerActions from './customer.actions'; 2 | import { Customer } from './customer.model'; 3 | 4 | describe('Customer Actions', () => { 5 | const customer = { id: 1, name: 'Test User' }; 6 | 7 | describe('Load Customers', () => { 8 | test('should create Customer Load Action', () => { 9 | const action = new CustomerActions.Load(); 10 | 11 | expect(action.type).toMatchSnapshot(); 12 | }); 13 | }); 14 | 15 | describe('Load Customers Success', () => { 16 | test('should create Customer Load Success Action', () => { 17 | const payload = [customer], 18 | action = new CustomerActions.LoadSuccess(payload); 19 | 20 | expect(action.type).toMatchSnapshot(); 21 | expect(action.payload).toMatchSnapshot(); 22 | }); 23 | }); 24 | 25 | describe('Load Customers Success', () => { 26 | test('should create Customer Load Fail Action', () => { 27 | const error = { status: 1, error: 'Error loading customer' }, 28 | action = new CustomerActions.LoadFail(error); 29 | 30 | expect(action.type).toMatchSnapshot(); 31 | expect(action.error).toMatchSnapshot(); 32 | }); 33 | }); 34 | 35 | describe('Customer Select', () => { 36 | test('should set payload to customer', () => { 37 | const action = new CustomerActions.Select(customer); 38 | 39 | expect(action.type).toMatchSnapshot(); 40 | expect(action.payload).toMatchSnapshot(); 41 | }); 42 | 43 | test('should set customer to payload in snapshot', () => { 44 | const action = new CustomerActions.Select(customer); 45 | 46 | expect(action.payload).toMatchSnapshot(); 47 | }); 48 | }); 49 | }); 50 | -------------------------------------------------------------------------------- /src/app/state/customer/customer.actions.ts: -------------------------------------------------------------------------------- 1 | import { Action } from '@ngrx/store'; 2 | import { Customer } from './customer.model'; 3 | 4 | export enum CustomerActionTypes { 5 | Load = '[Customer] Load', 6 | LoadSuccess = '[Customer] Load Success', 7 | LoadFail = '[Customer] Load Fail', 8 | Select = '[Customer] Select' 9 | } 10 | 11 | export class Load implements Action { 12 | readonly type = CustomerActionTypes.Load; 13 | } 14 | 15 | export class LoadSuccess implements Action { 16 | readonly type = CustomerActionTypes.LoadSuccess; 17 | 18 | constructor(public payload: Customer[]) {} 19 | } 20 | 21 | export class LoadFail implements Action { 22 | readonly type = CustomerActionTypes.LoadFail; 23 | 24 | constructor(public error: any) {} 25 | } 26 | 27 | export class Select implements Action { 28 | readonly type = CustomerActionTypes.Select; 29 | 30 | constructor(public payload: Customer) {} 31 | } 32 | 33 | export type CustomerActions = Load | LoadSuccess | LoadFail | Select; 34 | -------------------------------------------------------------------------------- /src/app/state/customer/customer.effects.spec.ts: -------------------------------------------------------------------------------- 1 | import { TestBed } from '@angular/core/testing'; 2 | import { CustomersService } from '@core/services/customer.service'; 3 | import { Actions } from '@ngrx/effects'; 4 | import { cold, hot } from 'jasmine-marbles'; 5 | import { Observable } from 'rxjs/Observable'; 6 | import { empty } from 'rxjs/observable/empty'; 7 | import { Load, LoadFail, LoadSuccess } from './customer.actions'; 8 | import { CustomerEffects } from './customer.effects'; 9 | import { Customer } from './customer.model'; 10 | 11 | export class TestActions extends Actions { 12 | constructor() { 13 | super(empty()); 14 | } 15 | 16 | set stream(source: Observable) { 17 | this.source = source; 18 | } 19 | } 20 | 21 | export function getActions() { 22 | return new TestActions(); 23 | } 24 | 25 | describe('CustomerEffects', () => { 26 | let effects: CustomerEffects; 27 | let actions$: TestActions; 28 | let customersService: any; 29 | 30 | const customer1 = { id: 1, name: 'User 1' } as Customer, 31 | customer2 = { id: 2, name: 'User 2' } as Customer, 32 | customers = [customer1, customer2]; 33 | 34 | beforeEach(() => { 35 | TestBed.configureTestingModule({ 36 | providers: [ 37 | CustomerEffects, 38 | { 39 | provide: CustomersService, 40 | useValue: { load: jest.fn() } 41 | }, 42 | { 43 | provide: Actions, 44 | useFactory: getActions 45 | } 46 | ] 47 | }); 48 | 49 | effects = TestBed.get(CustomerEffects); 50 | customersService = TestBed.get(CustomersService); 51 | actions$ = TestBed.get(Actions); 52 | }); 53 | 54 | describe('load$', () => { 55 | it('should return a new customer.LoadSuccess, with the customers, on success', () => { 56 | const action = new Load(), 57 | completion = new LoadSuccess(customers), 58 | response = cold('a|', { a: customers }), 59 | expected = cold('-b', { b: completion }); 60 | 61 | actions$.stream = hot('-a', { a: action }); 62 | 63 | // mock the load function to be the response 64 | customersService.load = jest.fn(() => response); 65 | 66 | expect(effects.load$).toMatchSnapshot(); 67 | }); 68 | 69 | it('should return a new customer.LoadError, on fail', () => { 70 | const action = new Load(), 71 | completion = new LoadFail('error'), 72 | response = cold('#'), 73 | expected = cold('-b', { b: completion }); 74 | 75 | actions$.stream = hot('-a', { a: action }); 76 | 77 | // mock the load function to be the response 78 | customersService.load = jest.fn(() => response); 79 | 80 | expect(effects.load$).toMatchSnapshot(); 81 | }); 82 | }); 83 | }); 84 | -------------------------------------------------------------------------------- /src/app/state/customer/customer.effects.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | import { CustomersService } from '@core/services/customer.service'; 3 | import { Actions, Effect, ofType } from '@ngrx/effects'; 4 | import { Action } from '@ngrx/store'; 5 | import { Observable } from 'rxjs/Observable'; 6 | import { of } from 'rxjs/observable/of'; 7 | import { catchError, map, switchMap } from 'rxjs/operators'; 8 | import { 9 | CustomerActionTypes, 10 | Load, 11 | LoadFail, 12 | LoadSuccess 13 | } from './customer.actions'; 14 | import { Customer } from './customer.model'; 15 | 16 | @Injectable() 17 | export class CustomerEffects { 18 | @Effect() 19 | load$: Observable = this.actions$.pipe( 20 | ofType(CustomerActionTypes.Load), 21 | switchMap(query => { 22 | return this.customersService 23 | .load() 24 | .pipe( 25 | map((customers: Customer[]) => new LoadSuccess(customers)), 26 | catchError(err => of(new LoadFail(err))) 27 | ); 28 | }) 29 | ); 30 | 31 | constructor( 32 | private actions$: Actions, 33 | private customersService: CustomersService 34 | ) {} 35 | } 36 | -------------------------------------------------------------------------------- /src/app/state/customer/customer.model.ts: -------------------------------------------------------------------------------- 1 | export interface Customer { 2 | id: number; 3 | name: string; 4 | } 5 | -------------------------------------------------------------------------------- /src/app/state/customer/customer.reducer.spec.ts: -------------------------------------------------------------------------------- 1 | import { reducer } from './customer.reducer'; 2 | import * as fromCustomers from './customer.reducer'; 3 | import * as selectors from '.'; 4 | import { Load, LoadSuccess, LoadFail, Select } from './customer.actions'; 5 | import { Customer } from './customer.model'; 6 | 7 | describe('CustomersReducer', () => { 8 | const initialState: fromCustomers.State = { 9 | ids: [], 10 | entities: {}, 11 | loading: false, 12 | selectedCustomerId: null, 13 | error: null 14 | }, 15 | customers = [ 16 | { id: 1, name: 'test1' }, 17 | { id: 2, name: 'test2' }, 18 | { id: 3, name: 'test3' } 19 | ], 20 | customer = customers[0]; 21 | 22 | describe('undefined action', () => { 23 | it('should return the default state', () => { 24 | const result = reducer(undefined, {} as any); 25 | 26 | expect(result).toMatchSnapshot(); 27 | }); 28 | }); 29 | 30 | describe('Load Customers Action', () => { 31 | test('should set loading to true', () => { 32 | const action = new Load(), 33 | result = reducer(initialState, action); 34 | 35 | expect(result).toMatchSnapshot(); 36 | expect(fromCustomers.getLoading(result)).toBe(true); 37 | }); 38 | }); 39 | 40 | describe('Load Customers Success Action', () => { 41 | test('should add customers to state', () => { 42 | const action = new LoadSuccess(customers), 43 | result = reducer(initialState, action); 44 | 45 | expect(result).toMatchSnapshot(); 46 | }); 47 | }); 48 | 49 | describe('Load Customers Fail Action', () => { 50 | test('should add error to state', () => { 51 | const action = new LoadFail({ status: 1 }), 52 | result = reducer(initialState, action), 53 | error = 'Error loading customers'; 54 | 55 | expect(result).toMatchSnapshot(); 56 | expect(fromCustomers.getError(result)).toEqual(error); 57 | }); 58 | }); 59 | 60 | describe('Customer Select Action', () => { 61 | test('should set selectedCustomerId', () => { 62 | const action = new Select(customer), 63 | result = reducer(initialState, action); 64 | 65 | expect(result).toMatchSnapshot(); 66 | expect(fromCustomers.getSelectedId(result)).toEqual(customer.id); 67 | }); 68 | }); 69 | 70 | describe('GetSelectedCustomer selector', () => { 71 | test('should select customer', () => { 72 | const action = new LoadSuccess(customers); 73 | let result = reducer(initialState, action); 74 | 75 | result = reducer(result, new Select(customer)); 76 | 77 | expect(selectors.getSelectedCustomer.projector(result.entities, result.selectedCustomerId)).toMatchSnapshot(); 78 | }); 79 | }); 80 | }); 81 | -------------------------------------------------------------------------------- /src/app/state/customer/customer.reducer.ts: -------------------------------------------------------------------------------- 1 | import { createEntityAdapter, EntityAdapter, EntityState } from '@ngrx/entity'; 2 | 3 | import { Customer } from './customer.model'; 4 | import { CustomerActions, CustomerActionTypes } from './customer.actions'; 5 | 6 | export interface State extends EntityState { 7 | selectedCustomerId: number; 8 | loading: boolean; 9 | error: string; 10 | } 11 | 12 | export const adapter: EntityAdapter = createEntityAdapter(); 13 | 14 | export const initialState: State = adapter.getInitialState({ 15 | selectedCustomerId: null, 16 | loading: false, 17 | error: null 18 | }); 19 | 20 | export function reducer(state = initialState, action: CustomerActions): State { 21 | switch (action.type) { 22 | case CustomerActionTypes.Load: 23 | return { ...state, loading: true, selectedCustomerId: null }; 24 | 25 | case CustomerActionTypes.LoadSuccess: { 26 | return { ...adapter.addMany(action.payload, state) }; 27 | } 28 | 29 | case CustomerActionTypes.LoadFail: { 30 | console.log(action.error); 31 | return { ...state, error: 'Error loading customers' }; 32 | } 33 | 34 | case CustomerActionTypes.Select: { 35 | return { 36 | ...state, 37 | selectedCustomerId: action.payload.id 38 | }; 39 | } 40 | 41 | default: { 42 | return state; 43 | } 44 | } 45 | } 46 | 47 | export const getSelectedId = (state: State) => state.selectedCustomerId; 48 | export const getLoading = (state: State) => state.loading; 49 | export const getError = (state: State) => state.error; 50 | -------------------------------------------------------------------------------- /src/app/state/customer/index.ts: -------------------------------------------------------------------------------- 1 | import { createSelector, createFeatureSelector } from '@ngrx/store'; 2 | 3 | import * as fromCustomers from './customer.reducer'; 4 | import { State as CustomersState } from './customer.reducer'; 5 | 6 | export const reducers = { 7 | customers: fromCustomers.reducer 8 | }; 9 | 10 | 11 | export const getCustomersState = createFeatureSelector( 12 | 'customer' 13 | ); 14 | 15 | export const { 16 | selectAll: getAllCustomers, 17 | selectEntities: getCustomerEntities, 18 | selectIds: getCustomerIds, 19 | selectTotal: getTotalCustomers 20 | } = fromCustomers.adapter.getSelectors(getCustomersState); 21 | 22 | export const getSelectedCustomerId = createSelector( 23 | getCustomersState, 24 | fromCustomers.getSelectedId 25 | ); 26 | 27 | export const getSelectedCustomer = createSelector( 28 | getCustomerEntities, 29 | fromCustomers.getSelectedId, 30 | (entities, id) => entities[id] 31 | ); 32 | 33 | export const getLoading = createSelector( 34 | getCustomersState, 35 | fromCustomers.getLoading 36 | ); 37 | 38 | export const getError = createSelector( 39 | getCustomersState, 40 | fromCustomers.getError 41 | ); 42 | -------------------------------------------------------------------------------- /src/app/state/shared/utils.ts: -------------------------------------------------------------------------------- 1 | import { Params, RouterStateSnapshot } from '@angular/router'; 2 | import { RouterStateSerializer } from '@ngrx/router-store'; 3 | 4 | /** 5 | * The RouterStateSerializer takes the current RouterStateSnapshot 6 | * and returns any pertinent information needed. The snapshot contains 7 | * all information about the state of the router at the given point in time. 8 | * The entire snapshot is complex and not always needed. In this case, you only 9 | * need the URL and query parameters from the snapshot in the store. Other items could be 10 | * returned such as route parameters and static route data. 11 | */ 12 | 13 | export interface RouterStateUrl { 14 | url: string; 15 | queryParams: Params; 16 | } 17 | 18 | export class CustomRouterStateSerializer 19 | implements RouterStateSerializer { 20 | serialize(routerState: RouterStateSnapshot): RouterStateUrl { 21 | const { url } = routerState; 22 | const queryParams = routerState.root.queryParams; 23 | return { url, queryParams }; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/app/state/state.module.ts: -------------------------------------------------------------------------------- 1 | import { CommonModule } from '@angular/common'; 2 | import { 3 | ModuleWithProviders, 4 | NgModule, 5 | Optional, 6 | SkipSelf 7 | } from '@angular/core'; 8 | import { environment } from '@env'; 9 | import { EffectsModule } from '@ngrx/effects'; 10 | import { 11 | RouterStateSerializer, 12 | StoreRouterConnectingModule 13 | } from '@ngrx/router-store'; 14 | import { StoreModule } from '@ngrx/store'; 15 | import { StoreDevtoolsModule } from '@ngrx/store-devtools'; 16 | import { CustomerEffects } from '@state/customer/customer.effects'; 17 | import { appMetaReducers, appReducer } from './app.reducer'; 18 | import { CustomRouterStateSerializer } from './shared/utils'; 19 | 20 | @NgModule({ 21 | imports: [ 22 | CommonModule, 23 | StoreRouterConnectingModule, 24 | StoreModule.forRoot(appReducer, { metaReducers: appMetaReducers }), 25 | EffectsModule.forRoot([CustomerEffects]), 26 | !environment.production ? StoreDevtoolsModule.instrument() : [] 27 | ], 28 | declarations: [] 29 | }) 30 | export class StateModule { 31 | static forRoot(): ModuleWithProviders { 32 | return { 33 | ngModule: StateModule, 34 | providers: [ 35 | /** 36 | * The `RouterStateSnapshot` provided by the `Router` is a large complex structure. 37 | * A custom RouterStateSerializer is used to parse the `RouterStateSnapshot` provided 38 | * by `@ngrx/router-store` to include only the desired pieces of the snapshot. 39 | */ 40 | { 41 | provide: RouterStateSerializer, 42 | useClass: CustomRouterStateSerializer 43 | } 44 | ] 45 | }; 46 | } 47 | 48 | constructor( 49 | @Optional() 50 | @SkipSelf() 51 | parentModule: StateModule 52 | ) { 53 | if (parentModule) { 54 | throw new Error( 55 | 'StateModule is already loaded. Import it in the AppModule only' 56 | ); 57 | } 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /src/assets/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/briebug/ngrx-jest-testing/6e855232c4d59ec4694157415a3ce8b23eacc2f3/src/assets/.gitkeep -------------------------------------------------------------------------------- /src/environments/environment.prod.ts: -------------------------------------------------------------------------------- 1 | export const environment = { 2 | production: true 3 | }; 4 | -------------------------------------------------------------------------------- /src/environments/environment.ts: -------------------------------------------------------------------------------- 1 | // The file contents for the current environment will overwrite these during build. 2 | // The build system defaults to the dev environment which uses `environment.ts`, but if you do 3 | // `ng build --env=prod` then `environment.prod.ts` will be used instead. 4 | // The list of which env maps to which file can be found in `.angular-cli.json`. 5 | 6 | export const environment = { 7 | production: false 8 | }; 9 | -------------------------------------------------------------------------------- /src/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/briebug/ngrx-jest-testing/6e855232c4d59ec4694157415a3ce8b23eacc2f3/src/favicon.ico -------------------------------------------------------------------------------- /src/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | NgrxJestTesting 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /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() 12 | .bootstrapModule(AppModule) 13 | .catch(err => console.log(err)); 14 | -------------------------------------------------------------------------------- /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/docs/ts/latest/guide/browser-support.html 15 | */ 16 | 17 | /*************************************************************************************************** 18 | * BROWSER POLYFILLS 19 | */ 20 | 21 | /** IE9, IE10 and IE11 requires all of the following polyfills. **/ 22 | // import 'core-js/es6/symbol'; 23 | // import 'core-js/es6/object'; 24 | // import 'core-js/es6/function'; 25 | // import 'core-js/es6/parse-int'; 26 | // import 'core-js/es6/parse-float'; 27 | // import 'core-js/es6/number'; 28 | // import 'core-js/es6/math'; 29 | // import 'core-js/es6/string'; 30 | // import 'core-js/es6/date'; 31 | // import 'core-js/es6/array'; 32 | // import 'core-js/es6/regexp'; 33 | // import 'core-js/es6/map'; 34 | // import 'core-js/es6/weak-map'; 35 | // import 'core-js/es6/set'; 36 | 37 | /** IE10 and IE11 requires the following for NgClass support on SVG elements */ 38 | // import 'classlist.js'; // Run `npm install --save classlist.js`. 39 | 40 | /** IE10 and IE11 requires the following for the Reflect API. */ 41 | // import 'core-js/es6/reflect'; 42 | 43 | 44 | /** Evergreen browsers require these. **/ 45 | // Used for reflect-metadata in JIT. If you use AOT (and only Angular decorators), you can remove. 46 | import 'core-js/es7/reflect'; 47 | 48 | 49 | /** 50 | * Required to support Web Animations `@angular/platform-browser/animations`. 51 | * Needed for: All but Chrome, Firefox and Opera. http://caniuse.com/#feat=web-animation 52 | **/ 53 | // import 'web-animations-js'; // Run `npm install --save web-animations-js`. 54 | 55 | 56 | 57 | /*************************************************************************************************** 58 | * Zone JS is required by default for Angular itself. 59 | */ 60 | import 'zone.js/dist/zone'; // Included with Angular CLI. 61 | 62 | 63 | 64 | /*************************************************************************************************** 65 | * APPLICATION IMPORTS 66 | */ 67 | -------------------------------------------------------------------------------- /src/setup-jest.ts: -------------------------------------------------------------------------------- 1 | import "jest-preset-angular"; 2 | 3 | Object.defineProperty(document.body.style, "transform", { 4 | value: () => { 5 | return { 6 | enumerable: true, 7 | configurable: true 8 | }; 9 | } 10 | }); 11 | -------------------------------------------------------------------------------- /src/styles.css: -------------------------------------------------------------------------------- 1 | /* You can add global styles to this file, and also import other style files */ 2 | -------------------------------------------------------------------------------- /src/sum.spec.ts: -------------------------------------------------------------------------------- 1 | const sumFunc = require('./sum'); 2 | 3 | test('adds 1 + 2 to equal 3', () => { 4 | expect(sumFunc.sum(1, 2)).toBe(3); 5 | }); 6 | -------------------------------------------------------------------------------- /src/sum.ts: -------------------------------------------------------------------------------- 1 | export function sum(a, b) { 2 | return a + b; 3 | } 4 | -------------------------------------------------------------------------------- /src/test-config.helper.ts: -------------------------------------------------------------------------------- 1 | import { TestBed } from '@angular/core/testing' 2 | 3 | type CompilerOptions = Partial<{ 4 | providers: any[] 5 | useJit: boolean 6 | preserveWhitespaces: boolean 7 | }> 8 | export type ConfigureFn = (testBed: typeof TestBed) => void 9 | 10 | export const configureTests = (configure: ConfigureFn, compilerOptions: CompilerOptions = {}) => { 11 | const compilerConfig: CompilerOptions = { 12 | preserveWhitespaces: false, 13 | ...compilerOptions, 14 | } 15 | 16 | const configuredTestBed = TestBed.configureCompiler(compilerConfig) 17 | 18 | configure(configuredTestBed) 19 | 20 | return configuredTestBed.compileComponents().then(() => configuredTestBed) 21 | } 22 | -------------------------------------------------------------------------------- /src/tsconfig.app.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "../tsconfig.json", 3 | "compilerOptions": { 4 | "outDir": "../out-tsc/app", 5 | "baseUrl": "./", 6 | "module": "es2015", 7 | "types": [] 8 | }, 9 | "exclude": [ 10 | "test.ts", 11 | "**/*.spec.ts" 12 | ] 13 | } 14 | -------------------------------------------------------------------------------- /src/tsconfig.spec.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "../tsconfig.json", 3 | "compilerOptions": { 4 | "outDir": "../out-tsc/spec", 5 | "baseUrl": "./", 6 | "module": "commonjs", 7 | "target": "es5", 8 | "types": [ 9 | "jasmine", 10 | "node" 11 | ] 12 | }, 13 | "files": [ 14 | "test.ts" 15 | ], 16 | "include": [ 17 | "**/*.spec.ts", 18 | "**/*.d.ts" 19 | ] 20 | } 21 | -------------------------------------------------------------------------------- /src/typings.d.ts: -------------------------------------------------------------------------------- 1 | /* SystemJS module definition */ 2 | declare var module: NodeModule; 3 | interface NodeModule { 4 | id: string; 5 | } 6 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compileOnSave": false, 3 | "compilerOptions": { 4 | "outDir": "./dist/out-tsc", 5 | "sourceMap": true, 6 | "declaration": false, 7 | "moduleResolution": "node", 8 | "emitDecoratorMetadata": true, 9 | "experimentalDecorators": true, 10 | "target": "es5", 11 | "typeRoots": [ 12 | "node_modules/@types" 13 | ], 14 | "lib": [ 15 | "es2017", 16 | "dom" 17 | ], 18 | "baseUrl": "./src", 19 | "paths": { 20 | "@state/*": [ 21 | "app/state/*" 22 | ], 23 | "@core/*": [ 24 | "app/core/*" 25 | ], 26 | "@app/*": [ 27 | "app/*" 28 | ], 29 | "@src/*": [ 30 | "./*" 31 | ], 32 | "@assets/*": [ 33 | "assets/*" 34 | ], 35 | "@env": [ 36 | "environments/environment" 37 | ] 38 | } 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /tslint.json: -------------------------------------------------------------------------------- 1 | { 2 | "rulesDirectory": [ 3 | "node_modules/codelyzer" 4 | ], 5 | "rules": { 6 | "arrow-return-shorthand": true, 7 | "callable-types": true, 8 | "class-name": true, 9 | "comment-format": [ 10 | true, 11 | "check-space" 12 | ], 13 | "curly": true, 14 | "deprecation": { 15 | "severity": "warn" 16 | }, 17 | "eofline": true, 18 | "forin": true, 19 | "import-blacklist": [ 20 | true, 21 | "rxjs", 22 | "rxjs/Rx" 23 | ], 24 | "import-spacing": true, 25 | "indent": [ 26 | true, 27 | "spaces" 28 | ], 29 | "interface-over-type-literal": true, 30 | "label-position": true, 31 | "max-line-length": [ 32 | true, 33 | 140 34 | ], 35 | "member-access": false, 36 | "member-ordering": [ 37 | true, 38 | { 39 | "order": [ 40 | "static-field", 41 | "instance-field", 42 | "static-method", 43 | "instance-method" 44 | ] 45 | } 46 | ], 47 | "no-arg": true, 48 | "no-bitwise": true, 49 | "no-console": [ 50 | true, 51 | "debug", 52 | "info", 53 | "time", 54 | "timeEnd", 55 | "trace" 56 | ], 57 | "no-construct": true, 58 | "no-debugger": true, 59 | "no-duplicate-super": true, 60 | "no-empty": false, 61 | "no-empty-interface": true, 62 | "no-eval": true, 63 | "no-inferrable-types": [ 64 | true, 65 | "ignore-params" 66 | ], 67 | "no-misused-new": true, 68 | "no-non-null-assertion": true, 69 | "no-shadowed-variable": true, 70 | "no-string-literal": false, 71 | "no-string-throw": true, 72 | "no-switch-case-fall-through": true, 73 | "no-trailing-whitespace": true, 74 | "no-unnecessary-initializer": true, 75 | "no-unused-expression": true, 76 | "no-use-before-declare": true, 77 | "no-var-keyword": true, 78 | "object-literal-sort-keys": false, 79 | "one-line": [ 80 | true, 81 | "check-open-brace", 82 | "check-catch", 83 | "check-else", 84 | "check-whitespace" 85 | ], 86 | "prefer-const": true, 87 | "quotemark": [ 88 | true, 89 | "single" 90 | ], 91 | "radix": true, 92 | "semicolon": [ 93 | true, 94 | "always" 95 | ], 96 | "triple-equals": [ 97 | true, 98 | "allow-null-check" 99 | ], 100 | "typedef-whitespace": [ 101 | true, 102 | { 103 | "call-signature": "nospace", 104 | "index-signature": "nospace", 105 | "parameter": "nospace", 106 | "property-declaration": "nospace", 107 | "variable-declaration": "nospace" 108 | } 109 | ], 110 | "typeof-compare": true, 111 | "unified-signatures": true, 112 | "variable-name": false, 113 | "whitespace": [ 114 | true, 115 | "check-branch", 116 | "check-decl", 117 | "check-operator", 118 | "check-separator", 119 | "check-type" 120 | ], 121 | "directive-selector": [ 122 | true, 123 | "attribute", 124 | "app", 125 | "camelCase" 126 | ], 127 | "component-selector": [ 128 | true, 129 | "element", 130 | "app", 131 | "kebab-case" 132 | ], 133 | "no-output-on-prefix": true, 134 | "use-input-property-decorator": true, 135 | "use-output-property-decorator": true, 136 | "use-host-property-decorator": true, 137 | "no-input-rename": true, 138 | "no-output-rename": true, 139 | "use-life-cycle-interface": true, 140 | "use-pipe-transform-interface": true, 141 | "component-class-suffix": true, 142 | "directive-class-suffix": true 143 | } 144 | } 145 | --------------------------------------------------------------------------------