├── .commitlintrc.json
├── .gitattributes
├── .gitignore
├── .huskyrc.json
├── .lintstagedrc.json
├── .prettierrc
├── .travis.yml
├── LICENSE
├── README.md
├── angular.json
├── jest.config.js
├── ngxs-testing.iml
├── package-lock.json
├── package.json
├── renovate.json
├── setupJest.ts
├── src
├── jest
│ ├── package.json
│ └── src
│ │ ├── jest-helpers.ts
│ │ └── public_api.ts
├── lib
│ ├── helpers
│ │ ├── ngxs-test.component.ts
│ │ └── ngxs-test.module.ts
│ ├── ngxs.setup.ts
│ └── symbol.ts
├── ng-package.json
├── package.json
├── public_api.ts
├── tests
│ └── ngxs.setup.spec.ts
├── tsconfig.lib.json
├── tsconfig.spec.json
└── tslint.json
├── tools
├── build.ts
└── copy-readme.ts
├── tsconfig.json
├── tsconfig.node.json
├── tslint.json
├── yarn.lock
└── yarn.lock.readme.md
/.commitlintrc.json:
--------------------------------------------------------------------------------
1 | {
2 | "extends": ["@commitlint/config-angular"]
3 | }
4 |
--------------------------------------------------------------------------------
/.gitattributes:
--------------------------------------------------------------------------------
1 | *.sh linguist-vendored=false
2 |
--------------------------------------------------------------------------------
/.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 | yarn-error.log
34 | testem.log
35 | /typings
36 |
37 | # System Files
38 | .DS_Store
39 | Thumbs.db
40 |
41 | .cache
42 |
--------------------------------------------------------------------------------
/.huskyrc.json:
--------------------------------------------------------------------------------
1 | {
2 | "hooks": {
3 | "pre-commit": "lint-staged",
4 | "commit-msg": "commitlint -E HUSKY_GIT_PARAMS"
5 | }
6 | }
7 |
--------------------------------------------------------------------------------
/.lintstagedrc.json:
--------------------------------------------------------------------------------
1 | {
2 | "*.ts": ["prettier --write", "git add"]
3 | }
4 |
--------------------------------------------------------------------------------
/.prettierrc:
--------------------------------------------------------------------------------
1 | {
2 | "printWidth": 120,
3 | "tabWidth": 4,
4 | "useTabs": false,
5 | "semi": true,
6 | "singleQuote": true,
7 | "trailingComma": "none",
8 | "htmlWhitespaceSensitivity": "css",
9 | "jsxBracketSameLine": true,
10 | "bracketSpacing": true,
11 | "arrowParens": "always",
12 | "proseWrap": "always"
13 | }
14 |
--------------------------------------------------------------------------------
/.travis.yml:
--------------------------------------------------------------------------------
1 | language: node_js
2 | sudo: false
3 | node_js:
4 | - "12.3.1"
5 | install:
6 | - npm install
7 | script:
8 | - npm run lint
9 | - npm test
10 | - npm run build
11 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
2 |
3 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
4 |
5 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
6 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | ---
6 |
7 | ## NGXS Testing
8 |
9 | [](https://travis-ci.org/ngxs-labs/testing)
10 | [](https://www.npmjs.com/package/@ngxs-labs/testing)
11 |
12 | ```
13 | $ npm install @ngxs-labs/testing --save-dev
14 | ```
15 |
16 | ### Introduction
17 |
18 | `@ngxs-labs/testing` is package for configures and initializes environment for ngxs unit testing and provides methods for creating states in unit tests.
19 |
20 | ### Simple example
21 |
22 | Unit testing is easy with NGXS.
23 |
24 | ```ts
25 | import { NgxsTestBed } from '@ngxs-labs/testing';
26 |
27 | describe('Zoo', () => {
28 |
29 | it('it toggles feed', async(() => {
30 | const { selectSnapshot, dispatch } = NgxsTestBed.configureTestingStates({ states: [ ZooState ] });
31 |
32 | dispatch(new FeedAnimals());
33 | const feed = selectSnapshot(state => state.zoo.feed);
34 |
35 | expect(feed).toBe(true);
36 | }));
37 |
38 | });
39 | ```
40 |
41 | ### Unit testing actions
42 |
43 | Use `getStateContextMocks` to mock and spy on the first argument of `@Actions` functions: the `StateContext`.
44 |
45 | With this state:
46 | ```ts
47 | @State({ name: ZOO_STATE_NAME, defaults: { animals: 1, visitors: 10 } })
48 | class ZooState {
49 | @Action(ResetAnimalAction)
50 | public reset(ctx: StateContext) {
51 | ctx.setState({ animals: 1, visitors: 10 });
52 | ctx.dispatch(new AddAnimalAction());
53 | }
54 |
55 | @Action(AddAnimalAction)
56 | public add(ctx: StateContext, { animalAmount }: AddAnimalAction) {
57 | const state = ctx.getState();
58 | ctx.patchState({ animals: state.animals + 1 });
59 | }
60 | }
61 | ```
62 |
63 | `getStateContextMocks` allows the following tests:
64 |
65 | ```ts
66 | it('should set state and dispatch new action', () => {
67 | const { dispatch, getStateContextMocks } = NgxsTestBed.configureTestingStates({
68 | states: [ZooState]
69 | });
70 | dispatch(new ResetAnimalAction());
71 |
72 | expect(getStateContextMocks[ZOO_STATE_NAME].setState).toHaveBeenCalledWith({ animals: 1, visitors: 10 });
73 |
74 | expect(getStateContextMocks[ZOO_STATE_NAME].dispatch).toHaveBeenCalledWith(new AddAnimalAction());
75 | expect(getStateContextMocks[ZOO_STATE_NAME].dispatch).toHaveBeenCalledTimes(1);
76 | });
77 |
78 | it('should get state and patch to new value', () => {
79 | const { dispatch, getStateContextMocks } = NgxsTestBed.configureTestingStates({
80 | states: [ZooState]
81 | });
82 | dispatch(new AddAnimalAction());
83 |
84 | expect(getStateContextMocks[ZOO_STATE_NAME].getState).toHaveBeenCalled();
85 | expect(getStateContextMocks[ZOO_STATE_NAME].patchState).toHaveBeenCalledWith({ animals: 2 });
86 | });
87 | ```
88 |
89 | ### Mock Select
90 |
91 | Use `mockSelect` to quickly mock selector in component.
92 | `mockSelect` provides a `Subject` allowing to trigger the mocked selector on demand and with any value.
93 | ```ts
94 | import { mockSelect } from '@ngxs-labs/testing/jest';
95 |
96 | describe('Select tests', () => {
97 | let foodSelectorSubject: Subject;
98 |
99 | beforeEach(() => {
100 | TestBed.configureTestingModule({
101 | ...
102 | imports: [
103 | ...
104 | NgxsModule.forRoot([ZooState])
105 | ]
106 | }).compileComponents();
107 |
108 | foodSelectorSubject = mockSelect(ZooState.feed);
109 |
110 | ...
111 | });
112 |
113 | it('should display mocked value', () => {
114 |
115 | foodSelectorSubject.next(10);
116 | fixture.detectChanges();
117 | ...
118 | expect(food).toEqual(10)
119 | });
120 | });
121 | ```
122 |
123 |
124 |
125 |
--------------------------------------------------------------------------------
/angular.json:
--------------------------------------------------------------------------------
1 | {
2 | "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
3 | "version": 1,
4 | "newProjectRoot": "projects",
5 | "projects": {
6 | "testing": {
7 | "root": "./",
8 | "sourceRoot": "src",
9 | "projectType": "library",
10 | "prefix": "",
11 | "architect": {
12 | "build": {
13 | "builder": "@angular-devkit/build-ng-packagr:build",
14 | "options": {
15 | "tsConfig": "./src/tsconfig.lib.json",
16 | "project": "./src/ng-package.json"
17 | }
18 | },
19 | "lint": {
20 | "builder": "@angular-devkit/build-angular:tslint",
21 | "options": {
22 | "tsConfig": [
23 | "src/tsconfig.lib.json",
24 | "src/tsconfig.spec.json"
25 | ],
26 | "exclude": [
27 | "**/node_modules/**"
28 | ]
29 | }
30 | }
31 | }
32 | }
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/jest.config.js:
--------------------------------------------------------------------------------
1 | var path = require('path');
2 |
3 | module.exports = {
4 | verbose: true,
5 | watch: false,
6 | cache: false,
7 | preset: 'jest-preset-angular',
8 | setupFilesAfterEnv: ['/setupJest.ts'],
9 | rootDir: path.resolve('.'),
10 | testMatch: ['/src/**/*.spec.ts'],
11 | collectCoverageFrom: ['/src/lib/**/*.ts', '/src/jest/**/*.ts' ],
12 | coverageReporters: ['json', 'lcovonly', 'lcov', 'text', 'html'],
13 | coveragePathIgnorePatterns: ['/node_modules/'],
14 | globals: {
15 | 'ts-jest': {
16 | tsConfig: '/tsconfig.json',
17 | allowSyntheticDefaultImports: true
18 | }
19 | },
20 | moduleNameMapper: {
21 | "@ngxs-labs/testing/jest": "/src/jest/src/public_api.ts",
22 | "@ngxs-labs/testing": "/src/public_api.ts"
23 | },
24 | bail: true,
25 | collectCoverage: true,
26 | modulePathIgnorePatterns: ['/dist/'],
27 | modulePaths: ['']
28 | };
29 |
--------------------------------------------------------------------------------
/ngxs-testing.iml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "testing",
3 | "version": "0.0.0",
4 | "repository": {
5 | "type": "git",
6 | "url": "git+https://github.com/ngxs-labs/testing.git"
7 | },
8 | "license": "MIT",
9 | "scripts": {
10 | "ng": "ng",
11 | "lint": "ng lint",
12 | "test": "jest --config ./jest.config.js --coverage",
13 | "build": "ng build testing && ts-node --project tsconfig.node.json ./tools/copy-readme",
14 | "// - UTILS": "Utility scripts",
15 | "format": "prettier src/**/*.ts --write"
16 | },
17 | "private": true,
18 | "dependencies": {
19 | "@angular/common": "9.1.7",
20 | "@angular/compiler": "9.1.7",
21 | "@angular/core": "9.1.7",
22 | "@angular/platform-browser": "9.1.7",
23 | "@angular/platform-browser-dynamic": "9.1.7",
24 | "@ngxs/store": "3.6.2",
25 | "core-js": "2.6.5",
26 | "rxjs": "6.5.5",
27 | "zone.js": "~0.10.3"
28 | },
29 | "devDependencies": {
30 | "jest-preset-angular": "^7.1.1",
31 | "@angular-devkit/build-angular": "~0.901.7",
32 | "@angular-devkit/build-ng-packagr": "~0.901.7",
33 | "@angular/cli": "9.1.7",
34 | "@angular/compiler-cli": "9.1.9",
35 | "@commitlint/cli": "7.6.1",
36 | "@commitlint/config-angular": "7.6.0",
37 | "@types/jest": "24.9.1",
38 | "@types/node": "11.10.0",
39 | "@types/semver": "5.5.0",
40 | "@types/yargs": "12.0.11",
41 | "codelyzer": "^5.2.2",
42 | "husky": "2.7.0",
43 | "jest": "24.9.0",
44 | "lint-staged": "8.2.1",
45 | "ng-packagr": "^5.7.1",
46 | "npm-run-all": "4.1.5",
47 | "prettier": "1.19.1",
48 | "semver": "5.6.0",
49 | "ts-node": "8.10.1",
50 | "tsickle": "^0.38.1",
51 | "tslib": "1.12.0",
52 | "tslint": "5.20.1",
53 | "tslint-sonarts": "1.9.0",
54 | "typescript": "3.7.5",
55 | "yargs": "13.3.0"
56 | }
57 | }
58 |
--------------------------------------------------------------------------------
/renovate.json:
--------------------------------------------------------------------------------
1 | {
2 | "rangeStrategy": "bump",
3 | "separateMajorMinor": false,
4 | "timezone": "UTC",
5 | "automerge": true,
6 | "schedule": ["after 10pm every weekday", "before 4am every weekday", "every weekend"],
7 | "baseBranches": ["master"],
8 | "ignoreDeps": ["@types/node"],
9 | "packageFiles": ["package.json", "src/package.json"],
10 | "major": {
11 | "devDependencies": {
12 | "enabled": false
13 | }
14 | },
15 | "packageRules": [
16 | {
17 | "depTypeList": ["dependencies"],
18 | "packagePatterns": ["^@angular/.*"],
19 | "groupName": "@angular"
20 | },
21 | {
22 | "depTypeList": ["devDependencies"],
23 | "packagePatterns": ["^@angular.*"],
24 | "groupName": "@angular-dev"
25 | },
26 | {
27 | "packageNames": ["typescript"],
28 | "updateTypes": "patch"
29 | },
30 | {
31 | "packageNames": ["^@ngxs.*"],
32 | "groupName": "@ngxs"
33 | },
34 | {
35 | "packageNames": ["^rollup.*"],
36 | "groupName": "rollup"
37 | },
38 | {
39 | "packageNames": ["^@types/.*"],
40 | "groupName": "@types"
41 | }
42 | ]
43 | }
44 |
--------------------------------------------------------------------------------
/setupJest.ts:
--------------------------------------------------------------------------------
1 | import 'jest-preset-angular';
2 |
--------------------------------------------------------------------------------
/src/jest/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "ngPackage": {
3 | "$schema": "../../../node_modules/ng-packagr/ng-package.schema.json",
4 | "lib": {
5 | "entryFile": "src/public_api.ts",
6 | "flatModuleFile": "ngxs-testing-jest",
7 | "umdModuleIds": {
8 | "@ngxs/store": "ngxs-store",
9 | "@ngxs/store/internals": "ngxs-store-internals"
10 | }
11 | }
12 | }
13 | }
14 |
--------------------------------------------------------------------------------
/src/jest/src/jest-helpers.ts:
--------------------------------------------------------------------------------
1 | import { of, Subject } from 'rxjs';
2 | import { Store } from '@ngxs/store';
3 | import { TestBed } from '@angular/core/testing';
4 |
5 | class NgxsJestHelper {
6 | private static mockedSelector: { key: any; value: Subject }[] = [];
7 |
8 | static mockSelect(selectorFn: (state: any) => T): Subject {
9 | const store: Store = TestBed.get(Store);
10 | if (!jest.isMockFunction(store.select)) {
11 | jest.spyOn(store, 'select').mockImplementation((selector) => {
12 | const match = NgxsJestHelper.mockedSelector.find((s) => s.key === selector);
13 | if (match) {
14 | return match.value;
15 | }
16 | return of();
17 | });
18 | }
19 |
20 | const subject = new Subject();
21 | NgxsJestHelper.mockedSelector = [
22 | ...NgxsJestHelper.mockedSelector.filter((s) => s.key !== selectorFn),
23 | { key: selectorFn, value: subject }
24 | ];
25 | return subject;
26 | }
27 | }
28 |
29 | export const mockSelect = NgxsJestHelper.mockSelect;
30 |
--------------------------------------------------------------------------------
/src/jest/src/public_api.ts:
--------------------------------------------------------------------------------
1 | export { mockSelect } from './jest-helpers';
2 |
--------------------------------------------------------------------------------
/src/lib/helpers/ngxs-test.component.ts:
--------------------------------------------------------------------------------
1 | import { AfterViewInit, Component, OnInit } from '@angular/core';
2 |
3 | @Component({
4 | selector: 'app-root',
5 | template: ''
6 | })
7 | export class NgxsTestComponent implements OnInit, AfterViewInit {
8 | public ngOnInit(): void {}
9 | public ngAfterViewInit(): void {}
10 | }
11 |
--------------------------------------------------------------------------------
/src/lib/helpers/ngxs-test.module.ts:
--------------------------------------------------------------------------------
1 | import { ApplicationRef, NgModule } from '@angular/core';
2 | import { BrowserModule } from '@angular/platform-browser';
3 |
4 | import { NgxsTestComponent } from './ngxs-test.component';
5 |
6 | @NgModule({
7 | imports: [BrowserModule],
8 | declarations: [NgxsTestComponent],
9 | entryComponents: [NgxsTestComponent]
10 | })
11 | export class NgxsTestModule {
12 | public static ngDoBootstrap(app: ApplicationRef): void {
13 | app.bootstrap(NgxsTestComponent);
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/src/lib/ngxs.setup.ts:
--------------------------------------------------------------------------------
1 | import 'core-js/es6/reflect';
2 | import 'core-js/es7/reflect';
3 | import 'zone.js/dist/zone';
4 |
5 | import { ApplicationRef, Type } from '@angular/core';
6 | import { TestBed, TestBedStatic } from '@angular/core/testing';
7 | import { DOCUMENT } from '@angular/common';
8 | import { ɵBrowserDomAdapter as BrowserDomAdapter } from '@angular/platform-browser';
9 | import { BrowserDynamicTestingModule, platformBrowserDynamicTesting } from '@angular/platform-browser-dynamic/testing';
10 | import { NgxsModule, StateContext, Store } from '@ngxs/store';
11 |
12 | import { NgxsTestModule } from './helpers/ngxs-test.module';
13 | import {
14 | DispatchFn,
15 | NgxsOptionsTesting,
16 | NgxsTesting,
17 | ResetFn,
18 | SelectFn,
19 | SelectSnapshotFn,
20 | SnapshotFn,
21 | StateContextMap
22 | } from './symbol';
23 | import { NGXS_STATE_CONTEXT_FACTORY } from '@ngxs/store/internals';
24 | import { of } from 'rxjs';
25 | import { MappedStore } from '@ngxs/store/src/internal/internals';
26 |
27 | export class NgxsTestBed {
28 | public static configureTestingStates(options: NgxsOptionsTesting): NgxsTesting {
29 | function getStateCtxMocks(states: Type[]): StateContextMap {
30 | function createMockStateContext(stateClass: Type): StateContext {
31 | const { defaults, name } = stateClass['NGXS_OPTIONS_META'];
32 | const store: Store = TestBed.get(Store);
33 |
34 | return {
35 | getState: jest.fn().mockImplementation(() => defaults),
36 | setState: jest.fn().mockImplementation((val: T) => {
37 | store.reset({ [name]: val });
38 | }),
39 | patchState: jest.fn().mockImplementation((val: Partial) => {
40 | store.reset({ [name]: { ...defaults, ...val } });
41 | }),
42 | dispatch: jest.fn().mockImplementation(() => of())
43 | };
44 | }
45 |
46 | function mockCreateStateContext(mocksTest: {
47 | [key: string]: StateContext;
48 | }): (arg: unknown) => any {
49 | return ((state: MappedStore) => {
50 | return mocksTest[state.name];
51 | }) as (arg: unknown) => any;
52 | }
53 |
54 | const stateContextFactory = TestBed.get(NGXS_STATE_CONTEXT_FACTORY);
55 | const mocks: { [key: string]: StateContext } = states.reduce(
56 | (acc, state) => ({ ...acc, [state['NGXS_OPTIONS_META'].name]: createMockStateContext(state) }),
57 | {}
58 | );
59 |
60 | jest.spyOn(stateContextFactory, 'createStateContext').mockImplementation(mockCreateStateContext(mocks));
61 |
62 | return mocks;
63 | }
64 |
65 | this.resetTestBed();
66 |
67 | if (options.before) {
68 | options.before();
69 | }
70 |
71 | TestBed.configureTestingModule({
72 | imports: [
73 | NgxsTestModule,
74 | NgxsModule.forRoot(options.states || [], options.ngxsOptions || {}),
75 | ...(options.imports || [])
76 | ],
77 | providers: options.providers || []
78 | }).compileComponents();
79 |
80 | NgxsTestBed.ngxsBootstrap();
81 |
82 | return {
83 | get store(): Store {
84 | return TestBed.get(Store);
85 | },
86 | get snapshot(): SnapshotFn {
87 | const store: Store = TestBed.get(Store);
88 | return store.snapshot.bind(store);
89 | },
90 | get dispatch(): DispatchFn {
91 | const store: Store = TestBed.get(Store);
92 | return store.dispatch.bind(store);
93 | },
94 | get selectSnapshot(): SelectSnapshotFn {
95 | const store: Store = TestBed.get(Store);
96 | return store.selectSnapshot.bind(store);
97 | },
98 | get select(): SelectFn {
99 | const store: Store = TestBed.get(Store);
100 | return store.select.bind(store);
101 | },
102 | get selectOnce(): SelectFn {
103 | const store: Store = TestBed.get(Store);
104 | return store.selectOnce.bind(store);
105 | },
106 | get reset(): ResetFn {
107 | const store: Store = TestBed.get(Store);
108 | return store.reset.bind(store);
109 | },
110 | get getTestBed(): TestBedStatic {
111 | return TestBed;
112 | },
113 | get getStateContextMocks(): StateContextMap {
114 | return getStateCtxMocks(options.states || []);
115 | }
116 | };
117 | }
118 |
119 | private static ngxsBootstrap(): void {
120 | NgxsTestBed.createRootNode();
121 | NgxsTestModule.ngDoBootstrap(TestBed.get(ApplicationRef));
122 | }
123 |
124 | private static resetTestBed(): void {
125 | TestBed.resetTestEnvironment();
126 | TestBed.initTestEnvironment(BrowserDynamicTestingModule, platformBrowserDynamicTesting());
127 | }
128 |
129 | private static createRootNode(selector = 'app-root'): void {
130 | const document: Document = TestBed.get(DOCUMENT);
131 | const adapter = new BrowserDomAdapter();
132 | const root = adapter.createElement(selector);
133 | const oldRoots = document.querySelectorAll(selector);
134 | oldRoots.forEach((oldRoot) => adapter.remove(oldRoot));
135 | document.body.appendChild(root);
136 | }
137 | }
138 |
--------------------------------------------------------------------------------
/src/lib/symbol.ts:
--------------------------------------------------------------------------------
1 | import { StateContext, Store } from '@ngxs/store';
2 | import { ModuleWithProviders, Provider, Type } from '@angular/core';
3 | import { TestBedStatic } from '@angular/core/testing';
4 | import { NgxsConfig } from '@ngxs/store/src/symbols';
5 | import { Observable } from 'rxjs';
6 |
7 | export interface NgxsOptionsTesting {
8 | states?: Type[];
9 | ngxsOptions?: Partial;
10 | imports?: ModuleWithProviders[];
11 | before?: () => void;
12 | providers?: Provider[];
13 | }
14 |
15 | export interface StateContextMap {
16 | [key: string]: StateContext;
17 | }
18 |
19 | export type ResetFn = (state: T) => T;
20 | export type SnapshotFn = () => T;
21 | export type DispatchFn = (event: U | U[]) => Observable;
22 | export type SelectFn =
23 | | ((selector: string) => Observable)
24 | | ((selector: Type) => Observable)
25 | | ((selector: any) => Observable);
26 |
27 | export type SelectSnapshotFn =
28 | | ((selector: string) => T)
29 | | ((selector: Type) => T)
30 | | ((selector: any) => T);
31 |
32 | export interface NgxsTesting {
33 | readonly store: Store;
34 | readonly getTestBed: TestBedStatic;
35 | readonly snapshot: SnapshotFn;
36 | readonly dispatch: DispatchFn;
37 | readonly selectSnapshot: SelectSnapshotFn;
38 | readonly select: SelectFn;
39 | readonly selectOnce: SelectFn;
40 | readonly reset: ResetFn;
41 | readonly getStateContextMocks: StateContextMap;
42 | }
43 |
--------------------------------------------------------------------------------
/src/ng-package.json:
--------------------------------------------------------------------------------
1 | {
2 | "$schema": "../node_modules/ng-packagr/package.schema.json",
3 | "lib": {
4 | "flatModuleFile": "ngxs-labs-testing",
5 | "entryFile": "./public_api.ts",
6 | "umdModuleIds": {
7 | "@ngxs/store": "ngxs-store",
8 | "@ngxs/store/internals": "ngxs-store-internals"
9 | }
10 | },
11 | "dest": "../dist/testing"
12 | }
13 |
--------------------------------------------------------------------------------
/src/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "@ngxs-labs/testing",
3 | "version": "0.0.3",
4 | "repository": {
5 | "type": "git",
6 | "url": "git+https://github.com/ngxs-labs/testing.git"
7 | },
8 | "license": "MIT",
9 | "homepage": "https://github.com/ngxs-labs/testing#readme",
10 | "bugs": {
11 | "url": "https://github.com/ngxs-labs/testing/issues"
12 | },
13 | "keywords": [
14 | "ngxs",
15 | "redux",
16 | "store"
17 | ],
18 | "sideEffects": true,
19 | "peerDependencies": {
20 | "@angular/core": "^9.1.7",
21 | "@ngxs/store": ">=3.6.2",
22 | "rxjs": ">=6.5.5"
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/src/public_api.ts:
--------------------------------------------------------------------------------
1 | export { NgxsTestBed } from './lib/ngxs.setup';
2 | export * from './lib/symbol';
3 |
--------------------------------------------------------------------------------
/src/tests/ngxs.setup.spec.ts:
--------------------------------------------------------------------------------
1 | import { Action, NgxsAfterBootstrap, NgxsModule, NgxsOnInit, Select, Selector, State, StateContext } from '@ngxs/store';
2 | import { Component } from '@angular/core';
3 | import { Observable, Subject } from 'rxjs';
4 | import { ComponentFixture, TestBed } from '@angular/core/testing';
5 | import { By } from '@angular/platform-browser';
6 | import { CommonModule } from '@angular/common';
7 | import { NgxsTestBed } from '@ngxs-labs/testing';
8 | import { mockSelect } from '@ngxs-labs/testing/jest';
9 |
10 | describe('Full testing NGXS States with NgxsTestBed', () => {
11 | it('should be correct testing lifecycle with NgxsTestBed', () => {
12 | @State({ name: 'app', defaults: { count: 0 } })
13 | class AppState implements NgxsOnInit, NgxsAfterBootstrap {
14 | public ngxsOnInit(ctx: StateContext): void {
15 | this.triggerLifecycle(ctx, 'AppState.ngxsOnInit');
16 | }
17 |
18 | public ngxsAfterBootstrap(ctx: StateContext): void {
19 | this.triggerLifecycle(ctx, 'AppState.ngxsAfterBootstrap');
20 | }
21 |
22 | private triggerLifecycle(ctx: StateContext, type: string): void {
23 | ctx.setState((state: any) => ({ ...state, [type]: true, count: state.count + 1 }));
24 | }
25 | }
26 |
27 | const { store } = NgxsTestBed.configureTestingStates({ states: [AppState] });
28 | expect(store.snapshot()).toEqual({
29 | app: {
30 | 'AppState.ngxsOnInit': true,
31 | 'AppState.ngxsAfterBootstrap': true,
32 | count: 2
33 | }
34 | });
35 | });
36 |
37 | it('should be correct testing feed', async () => {
38 | let feed: any = null;
39 |
40 | class FeedAction {
41 | public static type = 'zoo';
42 | constructor(public payload: number) {}
43 | }
44 |
45 | @State({ name: 'zoo', defaults: { feed: 1 } })
46 | class ZooState {
47 | @Action(FeedAction) public update(ctx: StateContext, { payload }: FeedAction) {
48 | ctx.setState({ feed: payload });
49 | }
50 | }
51 |
52 | const { dispatch, snapshot, selectSnapshot, select, selectOnce, reset } = NgxsTestBed.configureTestingStates({
53 | states: [ZooState]
54 | });
55 |
56 | dispatch(new FeedAction(2));
57 | expect(snapshot()).toEqual({ zoo: { feed: 2 } });
58 | expect(selectSnapshot(ZooState)).toEqual({ feed: 2 });
59 |
60 | dispatch(new FeedAction(3));
61 | select(ZooState).subscribe((state) => (feed = state));
62 | expect(feed).toEqual({ feed: 3 });
63 |
64 | dispatch(new FeedAction(4));
65 | selectOnce(ZooState).subscribe((state) => (feed = state));
66 | expect(feed).toEqual({ feed: 4 });
67 |
68 | reset({});
69 | expect(snapshot()).toEqual({});
70 | });
71 |
72 | it('should provide StateContextFactory for mocks', () => {
73 | const ZOO_STATE_NAME = 'zoo';
74 | const FOOD_STATE_NAME = 'food';
75 |
76 | class FeedAction {
77 | public static type = 'feed';
78 | constructor(public feedAmount: number) {}
79 | }
80 |
81 | class AddAnimalAction {
82 | public static type = 'addAnimal';
83 | constructor(public animalAmount: number) {}
84 | }
85 |
86 | class ResetAnimalAction {
87 | public static type = 'resetAnimal';
88 | constructor() {}
89 | }
90 |
91 | class CleanAction {
92 | public static type = 'clean';
93 | constructor(public cleanAmount: number) {}
94 | }
95 |
96 | @State({ name: ZOO_STATE_NAME, defaults: { animals: 1 } })
97 | class ZooState {
98 | @Action(ResetAnimalAction) public reset(ctx: StateContext) {
99 | ctx.patchState({ animals: 0 });
100 | ctx.dispatch(new AddAnimalAction(2));
101 | }
102 |
103 | @Action(AddAnimalAction) public add(ctx: StateContext, { animalAmount }: AddAnimalAction) {
104 | const state = ctx.getState();
105 | ctx.setState({ ...state, animals: state.animals + animalAmount });
106 | }
107 | }
108 |
109 | @State({ name: FOOD_STATE_NAME, defaults: { feed: 0, clean: 0 } })
110 | class FoodState {
111 | @Action(FeedAction) public feed(ctx: StateContext, { feedAmount }: FeedAction) {
112 | const state = ctx.getState();
113 | ctx.setState({ ...state, feed: state.feed + feedAmount });
114 | ctx.dispatch(new CleanAction(feedAmount));
115 | }
116 |
117 | @Action(CleanAction) public clean(ctx: StateContext, { cleanAmount }: CleanAction) {
118 | const state = ctx.getState();
119 | ctx.patchState({ ...state, clean: state.clean + cleanAmount });
120 | }
121 | }
122 |
123 | const { dispatch, getStateContextMocks } = NgxsTestBed.configureTestingStates({
124 | states: [ZooState, FoodState]
125 | });
126 |
127 | dispatch(new FeedAction(4));
128 | dispatch(new ResetAnimalAction());
129 |
130 | expect(getStateContextMocks[ZOO_STATE_NAME].patchState).toHaveBeenCalledWith({ animals: 0 });
131 | expect(getStateContextMocks[FOOD_STATE_NAME].patchState).not.toHaveBeenCalled();
132 |
133 | expect(getStateContextMocks[ZOO_STATE_NAME].setState).not.toHaveBeenCalled();
134 | expect(getStateContextMocks[FOOD_STATE_NAME].setState).toHaveBeenCalledWith({ feed: 4, clean: 0 });
135 |
136 | expect(getStateContextMocks[ZOO_STATE_NAME].getState).not.toHaveBeenCalled();
137 | expect(getStateContextMocks[FOOD_STATE_NAME].getState).toHaveBeenCalled();
138 |
139 | expect(getStateContextMocks[ZOO_STATE_NAME].dispatch).toHaveBeenCalledWith(new AddAnimalAction(2));
140 | expect(getStateContextMocks[ZOO_STATE_NAME].dispatch).toHaveBeenCalledTimes(1);
141 | expect(getStateContextMocks[FOOD_STATE_NAME].dispatch).toHaveBeenCalledWith(new CleanAction(4));
142 | expect(getStateContextMocks[FOOD_STATE_NAME].dispatch).toHaveBeenCalledTimes(1);
143 | });
144 | });
145 |
146 | describe('Select tests', () => {
147 | class FeedAction {
148 | public static type = 'zoo';
149 | constructor(public payload: number) {}
150 | }
151 |
152 | class AddAnimalsAction {
153 | public static type = 'add animals';
154 | constructor(public payload: number) {}
155 | }
156 |
157 | @State({ name: 'zoo', defaults: { feed: 0, animals: 0 } })
158 | class ZooState {
159 | @Selector()
160 | static feed(state: { feed: number; animals: number }) {
161 | return state.feed;
162 | }
163 |
164 | @Selector()
165 | static animals(state: { feed: number; animals: number }) {
166 | return state.animals;
167 | }
168 |
169 | @Action(FeedAction) public feed(ctx: StateContext, { payload }: FeedAction) {
170 | ctx.patchState({ feed: payload });
171 | }
172 |
173 | @Action(AddAnimalsAction) public animals(ctx: StateContext, { payload }: AddAnimalsAction) {
174 | const state = ctx.getState();
175 | ctx.patchState({ animals: state.animals + payload });
176 | }
177 | }
178 |
179 | @Component({
180 | template: `
181 | {{ foodSelector$ | async }}
182 | {{ animalsSelector$ | async }}
183 | `
184 | })
185 | class HostComponent {
186 | @Select(ZooState.feed) foodSelector$!: Observable;
187 | @Select(ZooState.animals) animalsSelector$!: Observable;
188 | }
189 |
190 | let foodSelectorSubject: Subject;
191 | let animalsSelectorSubject: Subject;
192 | let fixture: ComponentFixture;
193 | let component: HostComponent;
194 |
195 | beforeEach(() => {
196 | TestBed.configureTestingModule({
197 | declarations: [HostComponent],
198 | imports: [CommonModule, NgxsModule.forRoot([ZooState])]
199 | }).compileComponents();
200 |
201 | foodSelectorSubject = mockSelect(ZooState.feed);
202 | animalsSelectorSubject = mockSelect(ZooState.animals);
203 |
204 | fixture = TestBed.createComponent(HostComponent);
205 | component = fixture.componentInstance;
206 |
207 | fixture.detectChanges();
208 | });
209 |
210 | it('should display mocked value', () => {
211 | foodSelectorSubject.next(1);
212 | animalsSelectorSubject.next(2);
213 |
214 | fixture.detectChanges();
215 | expect(component).toBeTruthy();
216 |
217 | const span = fixture.debugElement.query(By.css('span'));
218 | expect(span.nativeElement.innerHTML).toMatch('1');
219 | const p = fixture.debugElement.query(By.css('p'));
220 | expect(p.nativeElement.innerHTML).toMatch('2');
221 | });
222 | });
223 |
--------------------------------------------------------------------------------
/src/tsconfig.lib.json:
--------------------------------------------------------------------------------
1 | {
2 | "extends": "../tsconfig.json",
3 | "compilerOptions": {
4 | "target": "es2015",
5 | "module": "es2015",
6 | "lib": [
7 | "dom",
8 | "es2016"
9 | ],
10 | "moduleResolution": "node",
11 | "declaration": true,
12 | "inlineSources": true,
13 | "importHelpers": true
14 | },
15 | "angularCompilerOptions": {
16 | "skipTemplateCodegen": true,
17 | "strictMetadataEmit": true,
18 | "fullTemplateTypeCheck": true,
19 | "strictInjectionParameters": true,
20 | "annotateForClosureCompiler": true,
21 | "flatModuleId": "AUTOGENERATED",
22 | "flatModuleOutFile": "AUTOGENERATED"
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/src/tsconfig.spec.json:
--------------------------------------------------------------------------------
1 | {
2 | "extends": "../tsconfig.json",
3 | "compilerOptions": {
4 | "module": "commonjs",
5 | "types": [
6 | "jest",
7 | "node"
8 | ]
9 | },
10 | "include": [
11 | "**/*.spec.ts",
12 | "**/*.d.ts"
13 | ]
14 | }
15 |
--------------------------------------------------------------------------------
/src/tslint.json:
--------------------------------------------------------------------------------
1 | {
2 | "extends": "../tslint.json"
3 | }
4 |
--------------------------------------------------------------------------------
/tools/build.ts:
--------------------------------------------------------------------------------
1 | import { ngPackagr } from 'ng-packagr';
2 | import { join } from 'path';
3 |
4 | async function buildPackage(): Promise {
5 | try {
6 | await ngPackagr()
7 | .forProject(join(__dirname, '../src/package.json'))
8 | .withTsConfig(join(__dirname, '../src/tsconfig.lib.json'))
9 | .build();
10 | } catch (e) {
11 | console.log(e);
12 | }
13 | }
14 |
15 | buildPackage();
16 |
--------------------------------------------------------------------------------
/tools/copy-readme.ts:
--------------------------------------------------------------------------------
1 | import { join } from 'path';
2 | import { existsSync, createReadStream, createWriteStream } from 'fs';
3 |
4 | import { name } from '../package.json';
5 |
6 | function copyReadmeAfterSuccessfulBuild(): void {
7 | const path = join(__dirname, '../README.md');
8 | const readmeDoesNotExist = !existsSync(path);
9 |
10 | if (readmeDoesNotExist) {
11 | return console.warn(`README.md doesn't exist on the root level!`);
12 | }
13 |
14 | createReadStream(path)
15 | .pipe(createWriteStream(join(__dirname, `../dist/${name}/README.md`)))
16 | .on('finish', () => {
17 | console.log(`Successfully copied README.md into dist/${name} folder!`);
18 | });
19 | }
20 |
21 | copyReadmeAfterSuccessfulBuild();
22 |
--------------------------------------------------------------------------------
/tsconfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "compileOnSave": false,
3 | "compilerOptions": {
4 | "baseUrl": "./",
5 | "paths": {
6 | "@ngxs-labs/testing/jest": ["src/jest/src/public_api.ts"],
7 | "@ngxs-labs/testing": ["src/public_api.ts"]
8 | },
9 | "target": "es2015",
10 | "typeRoots": ["node_modules/@types"],
11 | "lib": [
12 | "es2018",
13 | "dom"
14 | ],
15 | "esModuleInterop": true,
16 | "module": "esnext",
17 | "moduleResolution": "node",
18 | "strict": true,
19 | "allowJs": false,
20 | "sourceMap": true,
21 | "declaration": false,
22 | "resolveJsonModule": true,
23 | "noImplicitReturns": true,
24 | "noUnusedParameters": true,
25 | "emitDecoratorMetadata": true,
26 | "experimentalDecorators": true,
27 | "noFallthroughCasesInSwitch": true,
28 | "suppressImplicitAnyIndexErrors": true
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/tsconfig.node.json:
--------------------------------------------------------------------------------
1 | {
2 | "extends": "./tsconfig.json",
3 | "compilerOptions": {
4 | "module": "commonjs",
5 | "target": "es2017"
6 | }
7 | }
8 |
--------------------------------------------------------------------------------
/tslint.json:
--------------------------------------------------------------------------------
1 | {
2 | "rulesDirectory": ["node_modules/codelyzer"],
3 | "extends": ["tslint-sonarts"],
4 | "rules": {
5 | "arrow-return-shorthand": true,
6 | "callable-types": true,
7 | "class-name": true,
8 | "comment-format": [true, "check-space"],
9 | "curly": true,
10 | "deprecation": {
11 | "severity": "warn"
12 | },
13 | "eofline": true,
14 | "forin": true,
15 | "import-blacklist": [true, "rxjs/Rx"],
16 | "import-spacing": true,
17 | "indent": [true, "spaces"],
18 | "interface-over-type-literal": true,
19 | "label-position": true,
20 | "max-line-length": [true, 120],
21 | "member-access": false,
22 | "member-ordering": [
23 | true,
24 | {
25 | "order": ["static-field", "instance-field", "static-method", "instance-method"]
26 | }
27 | ],
28 | "no-arg": true,
29 | "no-bitwise": true,
30 | "no-console": [true, "debug", "info", "time", "timeEnd", "trace"],
31 | "no-construct": true,
32 | "no-debugger": true,
33 | "no-duplicate-super": true,
34 | "no-empty": false,
35 | "no-empty-interface": true,
36 | "no-eval": true,
37 | "no-inferrable-types": [true, "ignore-params"],
38 | "no-misused-new": true,
39 | "no-non-null-assertion": true,
40 | "no-string-literal": false,
41 | "no-string-throw": true,
42 | "no-switch-case-fall-through": true,
43 | "no-trailing-whitespace": true,
44 | "no-unnecessary-initializer": true,
45 | "no-unused-expression": true,
46 | "no-use-before-declare": true,
47 | "no-var-keyword": true,
48 | "object-literal-sort-keys": false,
49 | "one-line": [true, "check-open-brace", "check-catch", "check-else", "check-whitespace"],
50 | "prefer-const": true,
51 | "quotemark": [true, "single"],
52 | "radix": true,
53 | "semicolon": [true, "always"],
54 | "triple-equals": [true, "allow-null-check"],
55 | "typedef-whitespace": [
56 | true,
57 | {
58 | "call-signature": "nospace",
59 | "index-signature": "nospace",
60 | "parameter": "nospace",
61 | "property-declaration": "nospace",
62 | "variable-declaration": "nospace"
63 | }
64 | ],
65 | "unified-signatures": true,
66 | "variable-name": false,
67 | "whitespace": [true, "check-branch", "check-decl", "check-operator", "check-separator", "check-type"],
68 | "no-output-on-prefix": false,
69 | "no-inputs-metadata-property": true,
70 | "no-outputs-metadata-property": true,
71 | "no-host-metadata-property": true,
72 | "no-input-rename": true,
73 | "no-output-rename": true,
74 | "use-lifecycle-interface": true,
75 | "use-pipe-transform-interface": true,
76 | "component-class-suffix": false,
77 | "directive-class-suffix": [false],
78 | "component-selector": [false],
79 | "directive-selector": [false]
80 | }
81 | }
82 |
--------------------------------------------------------------------------------
/yarn.lock.readme.md:
--------------------------------------------------------------------------------
1 | All of our npm dependencies are locked via the `yarn.lock` file for the following reasons:
2 |
3 | - our project has lots of dependencies which update at unpredictable times, so it's important that
4 | we update them explicitly once in a while rather than implicitly when any of us runs `yarn install`
5 | - locked dependencies allow us to reuse yarn cache on travis, significantly speeding up our builds
6 | (by 5 minutes or more)
7 | - locked dependencies allow us to detect when node_modules folder is out of date after a branch switch
8 | which allows us to build the project with the correct dependencies every time
9 |
10 | Before changing a dependency, do the following:
11 |
12 | - make sure you are in sync with `upstream/master`: `git fetch upstream && git rebase upstream/master`
13 | - ensure that your `node_modules` directory is not stale by running `yarn install`
14 |
15 |
16 | To add a new dependency do the following: `yarn add --dev`
17 |
18 | To update an existing dependency do the following: run `yarn upgrade @ --dev`
19 | or `yarn upgrade --dev` to update to the latest version that matches version constraint
20 | in `package.json`
21 |
22 | To Remove an existing dependency do the following: run `yarn remove `
23 |
24 |
25 | Once you've changed the dependency, commit the changes to `package.json` & `yarn.lock`, and you are done.
26 |
--------------------------------------------------------------------------------