fix(test): move all test apps

This commit is contained in:
thomas
2023-10-18 10:35:53 +02:00
parent 058c7b04a0
commit 9a151be595
254 changed files with 273 additions and 273 deletions

View File

@@ -0,0 +1,36 @@
{
"extends": ["../../../.eslintrc.json"],
"ignorePatterns": ["!**/*"],
"overrides": [
{
"files": ["*.ts"],
"rules": {
"@angular-eslint/directive-selector": [
"error",
{
"type": "attribute",
"prefix": "app",
"style": "camelCase"
}
],
"@angular-eslint/component-selector": [
"error",
{
"type": "element",
"prefix": "app",
"style": "kebab-case"
}
]
},
"extends": [
"plugin:@nx/angular",
"plugin:@angular-eslint/template/process-inline-templates"
]
},
{
"files": ["*.html"],
"extends": ["plugin:@nx/angular-template"],
"rules": {}
}
]
}

View File

@@ -0,0 +1,38 @@
<h1>Table testing</h1>
> Author: Thomas Laforge
## Statement:
NOT IMPLEMENTED YET
<!-- We have a small application that send a title to a fake backend that you type inside a input.
If the title is correctly typed, you can send the request otherwise you get a nice error and the request is not sent.
You can play with it by running : `npx nx serve testing-table`.
The goal is to test this behavior with Testing library and Cypress
The file named `child.component.spec.ts` will let test your application using Testing Library. To run the test suits, you need to run `npx nx test testing-table`. You can also install [Jest Runner](https://marketplace.visualstudio.com/items?itemName=firsttris.vscode-jest-runner) to execute your test by clicking on the `Run` button above each `describe` or `it` blocks.
For testing cypress, you will execute your test inside the `child.component.cy.ts` and run `npx nx component-test testing-table` to execute your test suits. You can add the `--watch` flag to execute your test in watch mode.
I created some `it` blocks but feel free to add more test if you like to. -->
### Submitting your work
1. Fork the project
2. clone it
3. npm ci
4. `npx nx serve testing-table` to play with the application
5. `npx nx test testing-table` to test your application with Testing Library
6. `npx nx component-test testing-table --watch` to test your application with Cypress
7. _...work on it_
8. Commit your work
9. Submit a PR with a title beginning with **Answer:22** that I will review and other dev can review.
<a href="https://github.com/tomalaforge/angular-challenges/pulls?q=label%3A22+label%3Aanswer"><img src="https://img.shields.io/badge/-Solutions-green" alt="nested testing"/></a>
<a href='https://github.com/tomalaforge/angular-challenges/pulls?q=label%3A22+label%3A"answer+author"'><img src="https://img.shields.io/badge/-Author solution-important" alt="nested testing solution author"/></a>
<!-- <a href="{Blog post url}" target="_blank" rel="noopener noreferrer"><img src="https://img.shields.io/badge/-Blog post explanation-blue" alt="nested testing blog article"/></a> -->
_You can ask any question on_ <a href="https://twitter.com/laforge_toma" target="_blank" rel="noopener noreferrer"><img src="./../../logo/twitter.svg" height=20px alt="twitter"/></a>

View File

@@ -0,0 +1,6 @@
import { defineConfig } from 'cypress';
import { nxComponentTestingPreset } from '@nx/angular/plugins/component-testing';
export default defineConfig({
component: nxComponentTestingPreset(__filename),
});

View File

@@ -0,0 +1,5 @@
{
"name": "Using fixtures to represent data",
"email": "hello@cypress.io",
"body": "Fixtures are a great way to mock data for responses to routes"
}

View File

@@ -0,0 +1,42 @@
/// <reference types="cypress" />
import { mount } from 'cypress/angular';
// ***********************************************
// This example commands.ts shows you how to
// create various custom commands and overwrite
// existing commands.
//
// For more comprehensive examples of custom
// commands please read more here:
// https://on.cypress.io/custom-commands
// ***********************************************
declare global {
// eslint-disable-next-line @typescript-eslint/no-namespace
namespace Cypress {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
interface Chainable<Subject> {
login(email: string, password: string): void;
mount: typeof mount;
}
}
}
Cypress.Commands.add('mount', mount);
//
// -- This is a parent command --
Cypress.Commands.add('login', (email, password) => {
console.log('Custom command example: Login', email, password);
});
//
// -- This is a child command --
// Cypress.Commands.add("drag", { prevSubject: 'element'}, (subject, options) => { ... })
//
//
// -- This is a dual command --
// Cypress.Commands.add("dismiss", { prevSubject: 'optional'}, (subject, options) => { ... })
//
//
// -- This will overwrite an existing command --
// Cypress.Commands.overwrite("visit", (originalFn, url, options) => { ... })

View File

@@ -0,0 +1,12 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width,initial-scale=1.0" />
<title>testing-table Components App</title>
</head>
<body>
<div data-cy-root></div>
</body>
</html>

View File

@@ -0,0 +1,17 @@
// ***********************************************************
// This example support/component.ts is processed and
// loaded automatically before your test files.
//
// This is a great place to put global configuration and
// behavior that modifies Cypress.
//
// You can change the location of this file or turn off
// automatically serving support files with the
// 'supportFile' configuration option.
//
// You can read more here:
// https://on.cypress.io/configuration
// ***********************************************************
// Import commands.ts using ES2015 syntax:
import './commands';

View File

@@ -0,0 +1,18 @@
{
"extends": "../tsconfig.json",
"compilerOptions": {
"outDir": "../../../dist/out-tsc",
"module": "commonjs",
"types": ["cypress", "node"],
"sourceMap": false
},
"include": [
"support/**/*.ts",
"../cypress.config.ts",
"../**/*.cy.ts",
"../**/*.cy.tsx",
"../**/*.cy.js",
"../**/*.cy.jsx",
"../**/*.d.ts"
]
}

View File

@@ -0,0 +1,21 @@
/* eslint-disable */
export default {
displayName: 'testing-table',
preset: '../../../jest.preset.js',
setupFilesAfterEnv: ['<rootDir>/src/test-setup.ts'],
transform: {
'^.+\\.(ts|mjs|js|html)$': [
'jest-preset-angular',
{
tsconfig: '<rootDir>/tsconfig.spec.json',
stringifyContentPathRegex: '\\.(html|svg)$',
},
],
},
transformIgnorePatterns: ['node_modules/(?!.*\\.mjs$)'],
snapshotSerializers: [
'jest-preset-angular/build/serializers/no-ng-attributes',
'jest-preset-angular/build/serializers/ng-snapshot',
'jest-preset-angular/build/serializers/html-comment',
],
};

View File

@@ -0,0 +1,106 @@
{
"name": "testing-table",
"$schema": "../../../node_modules/nx/schemas/project-schema.json",
"projectType": "application",
"sourceRoot": "apps/testing/table/src",
"prefix": "app",
"targets": {
"build": {
"executor": "@angular-devkit/build-angular:browser",
"outputs": ["{options.outputPath}"],
"options": {
"outputPath": "dist/apps/testing/table",
"index": "apps/testing/table/src/index.html",
"main": "apps/testing/table/src/main.ts",
"polyfills": ["zone.js"],
"tsConfig": "apps/testing/table/tsconfig.app.json",
"inlineStyleLanguage": "scss",
"assets": [
"apps/testing/table/src/favicon.ico",
"apps/testing/table/src/assets"
],
"styles": ["apps/testing/table/src/styles.scss"],
"scripts": [],
"allowedCommonJsDependencies": ["seedrandom"]
},
"configurations": {
"production": {
"budgets": [
{
"type": "initial",
"maximumWarning": "500kb",
"maximumError": "1mb"
},
{
"type": "anyComponentStyle",
"maximumWarning": "2kb",
"maximumError": "4kb"
}
],
"outputHashing": "all"
},
"development": {
"buildOptimizer": false,
"optimization": false,
"vendorChunk": true,
"extractLicenses": false,
"sourceMap": true,
"namedChunks": true
}
},
"defaultConfiguration": "production"
},
"serve": {
"executor": "@angular-devkit/build-angular:dev-server",
"configurations": {
"production": {
"browserTarget": "testing-table:build:production"
},
"development": {
"browserTarget": "testing-table:build:development"
}
},
"defaultConfiguration": "development"
},
"extract-i18n": {
"executor": "@angular-devkit/build-angular:extract-i18n",
"options": {
"browserTarget": "testing-table:build"
}
},
"lint": {
"executor": "@nx/linter:eslint",
"outputs": ["{options.outputFile}"],
"options": {
"lintFilePatterns": [
"apps/testing/table/**/*.ts",
"apps/testing/table/**/*.html"
]
}
},
"test": {
"executor": "@nx/jest:jest",
"outputs": ["{workspaceRoot}/coverage/{projectRoot}"],
"options": {
"jestConfig": "apps/testing/table/jest.config.ts",
"passWithNoTests": true
},
"configurations": {
"ci": {
"ci": true,
"codeCoverage": true
}
}
},
"component-test": {
"executor": "@nx/cypress:cypress",
"options": {
"cypressConfig": "apps/testing/table/cypress.config.ts",
"testingType": "component",
"skipServe": true,
"devServerTarget": "testing-table:build"
}
}
},
"tags": []
}

View File

@@ -0,0 +1,10 @@
import { Component } from '@angular/core';
import { TableComponent } from './table.component';
@Component({
standalone: true,
imports: [TableComponent],
selector: 'app-root',
template: ` <app-table /> `,
})
export class AppComponent {}

View File

@@ -0,0 +1,98 @@
import { TestbedHarnessEnvironment } from '@angular/cdk/testing/testbed';
import { MatTableHarness } from '@angular/material/table/testing';
import { render } from '@testing-library/angular';
import userEvent from '@testing-library/user-event';
import { TableComponent } from './table.component';
describe('AppComponent', () => {
// let loader: HarnessLoader;
// let fixture: ComponentFixture<TableComponent>;
// let loader: HarnessLoader;
// beforeEach(async () => {
// const view = await render(TableComponent);
// fixture = view.fixture;
// loader = TestbedHarnessEnvironment.loader(fixture);
// });
it('error modal is displayed if you click on "Confirm" without inputing a name', async () => {
userEvent.setup();
const { fixture } = await render(TableComponent);
const loader = TestbedHarnessEnvironment.loader(fixture);
const tables = await loader.getAllHarnesses(MatTableHarness);
expect(tables.length).toBe(1);
// const confirmButton = await screen.findByRole('button', {
// name: /confirm/i,
// });
// await userEvent.click(confirmButton);
// const dialogControl = await screen.findByRole('dialog');
// expect(dialogControl).toBeInTheDocument();
// const errorTitle = await screen.findByRole('heading', {
// name: /error/i,
// });
// expect(errorTitle).toBeInTheDocument();
// const okButton = await screen.findByRole('button', {
// name: /ok/i,
// });
// await userEvent.click(okButton);
});
// test('error message is shown if you click "Cancel" in the confirmation modal after submitting a name', async () => {
// userEvent.setup();
// await render(AppComponent);
// const inputControl = await screen.getByRole('textbox');
// await userEvent.type(inputControl, 'toto');
// const confirmButton = await screen.findByRole('button', {
// name: /confirm/i,
// });
// await userEvent.click(confirmButton);
// const dialogControl = await screen.findByRole('dialog');
// expect(dialogControl).toBeInTheDocument();
// const profilTitle = await screen.findByRole('heading', {
// name: /profil/i,
// });
// expect(profilTitle).toBeInTheDocument();
// const cancelButton = await screen.findByRole('button', {
// name: /cancel/i,
// });
// await userEvent.click(cancelButton);
// const errorText = await screen.getByText('Name is invalid !!');
// expect(errorText).toBeInTheDocument();
// });
// test('confirm message is shown if you click "Confirm" in the confirmation modal after submitting a name', async () => {
// userEvent.setup();
// await render(AppComponent);
// const inputControl = await screen.getByRole('textbox');
// await userEvent.type(inputControl, 'toto');
// const confirmButton = await screen.findByRole('button', {
// name: /confirm/i,
// });
// await userEvent.click(confirmButton);
// const dialogControl = await screen.findByRole('dialog');
// expect(dialogControl).toBeInTheDocument();
// const profilTitle = await screen.findByRole('heading', {
// name: /profil/i,
// });
// expect(profilTitle).toBeInTheDocument();
// const confirmDialogButton = await screen.findByRole('button', {
// name: /confirm/i,
// });
// await userEvent.click(confirmDialogButton);
// const confirmText = await screen.getByText('Name has been submitted');
// expect(confirmText).toBeInTheDocument();
// });
});

View File

@@ -0,0 +1,162 @@
import { FakeBackendService } from '@angular-challenges/testing-table/backend';
import { AsyncPipe, DatePipe, NgIf } from '@angular/common';
import { AfterViewInit, Component, ViewChild, inject } from '@angular/core';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatInputModule } from '@angular/material/input';
import { MatPaginator, MatPaginatorModule } from '@angular/material/paginator';
import { MatProgressSpinnerModule } from '@angular/material/progress-spinner';
import { MatSort, MatSortModule, SortDirection } from '@angular/material/sort';
import { MatTableModule } from '@angular/material/table';
import { User } from '@ngneat/falso';
import { LetDirective } from '@ngrx/component';
import { ComponentStore, tapResponse } from '@ngrx/component-store';
import { map, pipe, startWith, switchMap, tap } from 'rxjs';
interface TableState {
loading: boolean;
error?: string;
users: User[];
}
@Component({
selector: 'app-table',
standalone: true,
imports: [
MatFormFieldModule,
MatInputModule,
MatTableModule,
MatSortModule,
MatPaginatorModule,
MatProgressSpinnerModule,
LetDirective,
NgIf,
AsyncPipe,
DatePipe,
],
template: `
<div class="example-container mat-elevation-z8">
<div class="example-loading-shade" *ngIf="loading$ | async">
<mat-spinner></mat-spinner>
<!-- <div class="example-rate-limit-reached" *ngIf="isRateLimitReached">
GitHub's API rate limit has been reached. It will be reset in one
minute.
</div> -->
</div>
<div class="example-table-container">
<table
mat-table
[dataSource]="(issues$ | async) ?? []"
class="example-table"
matSort>
<!-- Number Column -->
<ng-container matColumnDef="firstName">
<th mat-header-cell *matHeaderCellDef mat-sort-header>FirstName</th>
<td mat-cell *matCellDef="let row">{{ row.firstName }}</td>
</ng-container>
<!-- Title Column -->
<ng-container matColumnDef="lastName">
<th mat-header-cell *matHeaderCellDef mat-sort-header>LastName</th>
<td mat-cell *matCellDef="let row">{{ row.lastName }}</td>
</ng-container>
<!-- State Column -->
<ng-container matColumnDef="email">
<th mat-header-cell *matHeaderCellDef mat-sort-header>Email</th>
<td mat-cell *matCellDef="let row">{{ row.email }}</td>
</ng-container>
<!-- Created Column -->
<!-- <ng-container matColumnDef="created">
<th mat-header-cell *matHeaderCellDef mat-sort-header>Created</th>
<td mat-cell *matCellDef="let row">{{ row.created_at | date }}</td>
</ng-container> -->
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns"></tr>
</table>
</div>
<mat-paginator
[length]="resultsLength$ | async"
[pageSize]="30"
aria-label="Select page of GitHub search results"></mat-paginator>
</div>
`,
})
export class TableComponent
extends ComponentStore<TableState>
implements AfterViewInit
{
readonly displayedColumns = ['firstName', 'lastName', 'email'];
private api = inject(FakeBackendService);
readonly issues$ = this.select((s) => s.users).pipe(
tap((t) => console.log('UserNEw ', t))
);
readonly loading$ = this.select((s) => s.loading);
readonly error$ = this.select((s) => s.error);
readonly resultsLength$ = this.select((s) => 100);
// resultsLength = 0;
// isLoadingResults = true;
// isRateLimitReached = false;
@ViewChild(MatPaginator) paginator!: MatPaginator;
@ViewChild(MatSort) sort!: MatSort;
constructor() {
super({ loading: false, users: [] });
}
readonly loadData = this.effect<{
sortActive: keyof User;
sortDir: SortDirection;
pageIndex: number;
}>(
pipe(
tap((t) => console.log('cocou', t)),
tap(() => this.patchState({ loading: true, users: [] })),
switchMap(({ sortActive, sortDir, pageIndex }) =>
this.api.getUsers(sortActive, sortDir, pageIndex).pipe(
tap((t) => console.log('user', t)),
tapResponse(
(data) => this.patchState({ users: data, loading: false }),
(err) => this.patchState({ error: err as string, loading: false })
)
)
)
)
);
ngAfterViewInit(): void {
// due to ExpressionChangedAfterItHasBeenCheckedError
console.log('cocuo', this.sort, this.paginator);
this.loadData(
this.select({
sortActive: this.sort.sortChange.pipe(
map((s) => s.active as keyof User)
),
sortDir: this.sort.sortChange.pipe(map((s) => s.direction)),
pageIndex: this.paginator.page.pipe(map((p) => p.pageIndex)),
}).pipe(
startWith({
sortActive: this.sort.active as keyof User,
sortDir: this.sort.direction,
pageIndex: 1,
})
)
);
}
// applyFilter(event: Event) {
// const filterValue = (event.target as HTMLInputElement).value;
// this.dataSource.filter = filterValue.trim().toLowerCase();
// if (this.dataSource.paginator) {
// this.dataSource.paginator.firstPage();
// }
// }
}

View File

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

View File

@@ -0,0 +1,13 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>TestingTable</title>
<base href="/" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="icon" type="image/x-icon" href="favicon.ico" />
</head>
<body>
<app-root></app-root>
</body>
</html>

View File

@@ -0,0 +1,8 @@
import { provideHttpClient } from '@angular/common/http';
import { bootstrapApplication } from '@angular/platform-browser';
import { provideAnimations } from '@angular/platform-browser/animations';
import { AppComponent } from './app/app.component';
bootstrapApplication(AppComponent, {
providers: [provideAnimations(), provideHttpClient()],
}).catch((err) => console.error(err));

View File

@@ -0,0 +1,31 @@
@use '@angular/material' as mat;
@tailwind base;
@tailwind components;
@tailwind utilities;
/* You can add global styles to this file, and also import other style files */
@include mat.core();
$theme-primary: mat.define-palette(mat.$indigo-palette);
$theme-accent: mat.define-palette(mat.$pink-palette, A200, A100, A400);
$theme-warn: mat.define-palette(mat.$red-palette);
$theme: mat.define-light-theme(
(
color: (
primary: $theme-primary,
accent: $theme-accent,
warn: $theme-warn,
),
typography: mat.define-typography-config(),
)
);
@include mat.core-theme($theme);
@include mat.all-component-themes($theme);
// @include mat.form-field-theme($theme);
// @include mat.input-theme($theme);
// @include mat.paginator-theme($theme);

View File

@@ -0,0 +1,2 @@
import '@testing-library/jest-dom';
import 'jest-preset-angular/setup-jest';

View File

@@ -0,0 +1,14 @@
const { createGlobPatternsForDependencies } = require('@nx/angular/tailwind');
const { join } = require('path');
/** @type {import('tailwindcss').Config} */
module.exports = {
content: [
join(__dirname, 'src/**/!(*.stories|*.spec).{ts,html}'),
...createGlobPatternsForDependencies(__dirname),
],
theme: {
extend: {},
},
plugins: [],
};

View File

@@ -0,0 +1,20 @@
{
"extends": "./tsconfig.json",
"compilerOptions": {
"outDir": "../../../dist/out-tsc",
"types": []
},
"files": ["src/main.ts"],
"include": ["src/**/*.d.ts"],
"exclude": [
"jest.config.ts",
"src/**/*.test.ts",
"src/**/*.spec.ts",
"cypress/**/*",
"cypress.config.ts",
"**/*.cy.ts",
"**/*.cy.js",
"**/*.cy.tsx",
"**/*.cy.jsx"
]
}

View File

@@ -0,0 +1,7 @@
{
"extends": "./tsconfig.json",
"include": ["src/**/*.ts"],
"compilerOptions": {
"types": ["jest", "node"]
}
}

View File

@@ -0,0 +1,35 @@
{
"compilerOptions": {
"target": "es2022",
"useDefineForClassFields": false,
"forceConsistentCasingInFileNames": true,
"strict": true,
"noImplicitOverride": true,
"noPropertyAccessFromIndexSignature": true,
"noImplicitReturns": true,
"noFallthroughCasesInSwitch": true
},
"files": [],
"include": [],
"references": [
{
"path": "./tsconfig.app.json"
},
{
"path": "./tsconfig.spec.json"
},
{
"path": "./tsconfig.editor.json"
},
{
"path": "./cypress/tsconfig.json"
}
],
"extends": "../../../tsconfig.base.json",
"angularCompilerOptions": {
"enableI18nLegacyMessageIdFormat": false,
"strictInjectionParameters": true,
"strictInputAccessModifiers": true,
"strictTemplates": true
}
}

View File

@@ -0,0 +1,16 @@
{
"extends": "./tsconfig.json",
"compilerOptions": {
"outDir": "../../../dist/out-tsc",
"module": "commonjs",
"types": ["jest", "node", "@testing-library/jest-dom"],
"target": "ES2016"
},
"files": ["src/test-setup.ts"],
"include": [
"jest.config.ts",
"src/**/*.test.ts",
"src/**/*.spec.ts",
"src/**/*.d.ts"
]
}