feat(doc): move todo-list

This commit is contained in:
thomas
2023-10-17 23:14:16 +02:00
parent 05951bd4df
commit ad3824aa79
36 changed files with 41 additions and 42 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,13 @@
# Real-life Application
> Author: Thomas Laforge
### Run Application
```bash
npx nx serve test-todos-list
```
### Documentation and Instruction
Challenge documentation is [here](https://angular-challenges.vercel.app/challenges/testing/29-real-application/).

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-todos-list 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: 'test-todos-list',
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,108 @@
{
"name": "test-todos-list",
"$schema": "../../../node_modules/nx/schemas/project-schema.json",
"projectType": "application",
"sourceRoot": "apps/test/todos-list/src",
"prefix": "app",
"targets": {
"build": {
"executor": "@angular-devkit/build-angular:browser",
"outputs": ["{options.outputPath}"],
"options": {
"outputPath": "dist/apps/test/todos-list",
"index": "apps/test/todos-list/src/index.html",
"main": "apps/test/todos-list/src/main.ts",
"polyfills": ["zone.js"],
"tsConfig": "apps/test/todos-list/tsconfig.app.json",
"inlineStyleLanguage": "scss",
"assets": [
"apps/test/todos-list/src/favicon.ico",
"apps/test/todos-list/src/assets"
],
"styles": [
"apps/test/todos-list/src/styles.scss",
"./node_modules/@angular/material/prebuilt-themes/indigo-pink.css"
],
"scripts": []
},
"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": "test-todos-list:build:production"
},
"development": {
"browserTarget": "test-todos-list:build:development"
}
},
"defaultConfiguration": "development"
},
"extract-i18n": {
"executor": "@angular-devkit/build-angular:extract-i18n",
"options": {
"browserTarget": "test-todos-list:build"
}
},
"lint": {
"executor": "@nx/linter:eslint",
"outputs": ["{options.outputFile}"],
"options": {
"lintFilePatterns": [
"apps/test/todos-list/**/*.ts",
"apps/test/todos-list/**/*.html"
]
}
},
"test": {
"executor": "@nx/jest:jest",
"outputs": ["{workspaceRoot}/coverage/{projectRoot}"],
"options": {
"jestConfig": "apps/test/todos-list/jest.config.ts",
"passWithNoTests": true
},
"configurations": {
"ci": {
"ci": true,
"codeCoverage": true
}
}
},
"component-test": {
"executor": "@nx/cypress:cypress",
"options": {
"cypressConfig": "apps/test/todos-list/cypress.config.ts",
"testingType": "component",
"skipServe": true,
"devServerTarget": "test-todos-list:build"
}
}
},
"tags": []
}

View File

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

View File

@@ -0,0 +1,7 @@
import { ApplicationConfig } from '@angular/core';
import { provideAnimations } from '@angular/platform-browser/animations';
import { provideRouter } from '@angular/router';
import { APP_ROUTES } from './app.route';
export const appConfig: ApplicationConfig = {
providers: [provideAnimations(), provideRouter(APP_ROUTES)],
};

View File

@@ -0,0 +1,25 @@
import { Routes } from '@angular/router';
export const PARAM_TICKET_ID = 'ticketId';
export const APP_ROUTES: Routes = [
{
path: '',
pathMatch: 'full',
redirectTo: 'list',
},
{
path: 'list',
loadComponent: () =>
import('./list/list.component').then((m) => m.ListComponent),
},
{
path: `detail/:${PARAM_TICKET_ID}`,
loadComponent: () =>
import('./detail/detail.component').then((m) => m.DetailComponent),
},
{
path: '**',
redirectTo: 'list',
},
];

View File

@@ -0,0 +1,109 @@
import { Injectable } from '@angular/core';
import { Observable, delay, of, throwError } from 'rxjs';
export type User = {
id: number;
name: string;
};
export interface BaseTicket {
id: number;
description: string;
completed: boolean;
}
export interface Ticket extends BaseTicket {
assigneeId: number | null;
}
export interface TicketUser extends BaseTicket {
assignee: string;
}
function randomDelay() {
return Math.random() * 1000;
}
@Injectable({ providedIn: 'root' })
export class BackendService {
storedTickets: Ticket[] = [
{
id: 0,
description: 'Install a monitor arm',
assigneeId: 111,
completed: false,
},
{
id: 1,
description: 'Move the desk to the new location',
assigneeId: 111,
completed: false,
},
];
storedUsers: User[] = [
{ id: 111, name: 'Thomas' },
{ id: 222, name: 'Jack' },
];
lastId = 1;
private findTicketById = (id: number) =>
this.storedTickets.find((ticket) => ticket.id === +id);
private findUserById = (id: number) =>
this.storedUsers.find((user) => user.id === +id);
tickets() {
return of(this.storedTickets).pipe(delay(randomDelay()));
}
ticket(id: number): Observable<Ticket | undefined> {
return of(this.findTicketById(id)).pipe(delay(randomDelay()));
}
users() {
return of(this.storedUsers).pipe(delay(randomDelay()));
}
user(id: number) {
return of(this.findUserById(id)).pipe(delay(randomDelay()));
}
newTicket(payload: { description: string }) {
const newTicket: Ticket = {
id: ++this.lastId,
description: payload.description,
assigneeId: null,
completed: false,
};
this.storedTickets = this.storedTickets.concat(newTicket);
return of(newTicket).pipe(delay(randomDelay()));
}
assign(ticketId: number, userId: number) {
return this.update(ticketId, { assigneeId: userId });
}
complete(ticketId: number, completed: boolean) {
return this.update(ticketId, { completed });
}
update(ticketId: number, updates: Partial<Omit<Ticket, 'id'>>) {
const foundTicket = this.findTicketById(ticketId);
if (!foundTicket) {
return throwError(() => new Error('ticket not found'));
}
const updatedTicket = { ...foundTicket, ...updates };
this.storedTickets = this.storedTickets.map((t) =>
t.id === ticketId ? updatedTicket : t
);
return of(updatedTicket).pipe(delay(randomDelay()));
}
}

View File

@@ -0,0 +1,58 @@
import { AsyncPipe, NgIf } from '@angular/common';
import { Component, inject } from '@angular/core';
import { MatButtonModule } from '@angular/material/button';
import { MatProgressBarModule } from '@angular/material/progress-bar';
import { RouterLink } from '@angular/router';
import { LetDirective } from '@ngrx/component';
import { provideComponentStore } from '@ngrx/component-store';
import { DetailStore } from './detail.store';
@Component({
selector: 'app-detail',
standalone: true,
imports: [
MatButtonModule,
RouterLink,
NgIf,
AsyncPipe,
MatProgressBarModule,
LetDirective,
],
template: `
<h2 class="text-xl mb-2">Ticket Detail:</h2>
<ng-container *ngrxLet="vm$ as vm">
<mat-progress-bar
mode="query"
*ngIf="vm.loading"
class="mt-5"></mat-progress-bar>
<section *ngIf="vm.ticket as ticket" class="flex flex-col gap-4">
<div><span class="font-bold">Ticket:</span> {{ ticket.id }}</div>
<div>
<span class="font-bold">Description:</span> {{ ticket.description }}
</div>
<div>
<span class="font-bold">AssigneeId:</span> {{ ticket.assigneeId }}
</div>
<div>
<span class="font-bold">Is done:</span> {{ ticket.completed }}
</div>
</section>
</ng-container>
<button
class="mt-8"
[routerLink]="['/list']"
mat-flat-button
color="primary"
type="button">
Back
</button>
`,
providers: [provideComponentStore(DetailStore)],
host: {
class: 'p-5 block',
},
})
export class DetailComponent {
vm$ = inject(DetailStore).vm$;
}

View File

@@ -0,0 +1,67 @@
import { Injectable } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import {
ComponentStore,
OnStateInit,
tapResponse,
} from '@ngrx/component-store';
import { concatLatestFrom } from '@ngrx/effects';
import { pipe } from 'rxjs';
import { map, mergeMap, tap } from 'rxjs/operators';
import { PARAM_TICKET_ID } from '../app.route';
import { BackendService, Ticket } from '../backend.service';
export interface TicketState {
ticket?: Ticket;
loading: boolean;
error: unknown;
}
const initialState: TicketState = {
loading: false,
error: '',
};
@Injectable()
export class DetailStore
extends ComponentStore<TicketState>
implements OnStateInit
{
readonly ticket$ = this.select((state) => state.ticket);
readonly loading$ = this.select((state) => state.loading);
readonly error$ = this.select((state) => state.error);
readonly vm$ = this.select({
ticket: this.ticket$,
loading: this.loading$,
});
constructor(private backend: BackendService, private route: ActivatedRoute) {
super(initialState);
}
readonly loadTicket = this.effect<void>(
pipe(
concatLatestFrom(() =>
this.route.params.pipe(map((p) => p[PARAM_TICKET_ID]))
),
tap(() => this.patchState({ loading: true, error: '' })),
mergeMap(([, id]) =>
this.backend.ticket(id).pipe(
tapResponse(
(ticket) =>
this.patchState({
loading: false,
ticket,
}),
(error: unknown) => this.patchState({ error })
)
)
)
)
);
ngrxOnStateInit() {
this.loadTicket();
}
}

View File

@@ -0,0 +1,112 @@
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { ReactiveFormsModule } from '@angular/forms';
import { NoopAnimationsModule } from '@angular/platform-browser/animations';
import { RouterTestingModule } from '@angular/router/testing';
import { of } from 'rxjs';
import { BackendService } from '../backend.service';
import { ListComponent } from './list.component';
const USERS = [
{ id: 1, name: 'titi' },
{ id: 2, name: 'george' },
];
const TICKETS = [
{
id: 0,
description: 'Install a monitor arm',
assigneeId: 1,
completed: false,
},
{
id: 1,
description: 'Coucou',
assigneeId: 1,
completed: false,
},
];
describe('ListComponent', () => {
let component: ListComponent;
let fixture: ComponentFixture<ListComponent>;
//To change with a setup function
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [
ListComponent,
ReactiveFormsModule,
RouterTestingModule,
NoopAnimationsModule,
],
providers: [
{
provide: BackendService,
useValue: {
users: () => of(USERS),
tickets: () => of(TICKETS),
},
},
],
}).compileComponents();
});
beforeEach(() => {
fixture = TestBed.createComponent(ListComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
describe('Given Install inside the search input', () => {
it('Then one row is visible', async () => {
//
});
});
describe('When typing a description and clicking on add a new ticket', () => {
describe('Given a success answer from API', () => {
it('Then ticket with the description is added to the list with unassigned status', async () => {
//
});
});
describe('Given a failure answer from API', () => {
it('Then an error is displayed at the bottom of the list', async () => {
//
});
});
});
describe('When assigning first ticket to george', () => {
describe('Given a success answer from API', () => {
it('Then first ticket is assigned to George', async () => {
//
});
});
describe('Given a failure answer from API', () => {
it('Then an error is displayed at the bottom of the list', async () => {
//
});
});
});
describe('When finishing first ticket', () => {
describe('Given a success answer from API', () => {
it('Then first ticket is done', async () => {
//
});
});
describe('Given a failure answer from API', () => {
it('Then an error is displayed at the bottom of the list', async () => {
//
});
});
});
describe('When clicking on first ticket', () => {
it('Then we navigate to detail/0', async () => {
//
});
});
});

View File

@@ -0,0 +1,76 @@
import { NgFor, NgIf } from '@angular/common';
import { Component, OnInit, inject } from '@angular/core';
import { FormControl, ReactiveFormsModule } from '@angular/forms';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatInputModule } from '@angular/material/input';
import { MatProgressBarModule } from '@angular/material/progress-bar';
import { LetDirective } from '@ngrx/component';
import { provideComponentStore } from '@ngrx/component-store';
import { TicketStore } from './ticket.store';
import { AddComponent } from './ui/add.component';
import { RowComponent } from './ui/row.component';
@Component({
selector: 'app-list',
standalone: true,
imports: [
ReactiveFormsModule,
AddComponent,
RowComponent,
MatFormFieldModule,
MatProgressBarModule,
NgIf,
NgFor,
MatInputModule,
LetDirective,
],
template: `
<h2 class="text-xl mb-2">Tickets</h2>
<mat-form-field appearance="fill">
<mat-label>Search</mat-label>
<input
type="text"
matInput
[formControl]="search"
placeholder="write an article" />
</mat-form-field>
<ng-container *ngrxLet="vm$ as vm">
<app-add
[loading]="vm.loading"
(addTicket)="ticketStore.addTicket($event)"></app-add>
<mat-progress-bar
mode="query"
*ngIf="vm.loading"
class="mt-5"></mat-progress-bar>
<ul class="flex flex-col gap-4 max-w-3xl">
<app-row
*ngFor="let t of vm.tickets"
[ticket]="t"
[users]="vm.users"
(assign)="ticketStore.assignTicket($event)"
(closeTicket)="ticketStore.done($event)">
</app-row>
</ul>
<footer class="text-red-500">
{{ vm.error }}
</footer>
</ng-container>
`,
providers: [provideComponentStore(TicketStore)],
host: {
class: 'p-5 block',
},
})
export class ListComponent implements OnInit {
ticketStore = inject(TicketStore);
readonly vm$ = this.ticketStore.vm$;
search = new FormControl();
ngOnInit(): void {
this.ticketStore.search(this.search.valueChanges);
}
}

View File

@@ -0,0 +1,29 @@
describe('TicketStore', () => {
describe('When init', () => {
it('Then calls backend.users', async () => {
//
});
it('Then calls backend.tickets', async () => {
//
});
describe('Given all api returns success response', () => {
it('Then tickets and users should be merged ', async () => {
//
});
});
describe('Given users api returns failure response', () => {
it('Then tickets should not have any assignee', () => {
//
});
});
describe('When adding a new ticket with success', () => {
it('Then ticket is added to the list', async () => {
//
});
});
});
});

View File

@@ -0,0 +1,180 @@
import { Injectable, inject } from '@angular/core';
import {
ComponentStore,
OnStateInit,
OnStoreInit,
tapResponse,
} from '@ngrx/component-store';
import { pipe } from 'rxjs';
import { mergeMap, tap } from 'rxjs/operators';
import { BackendService, Ticket, User } from '../backend.service';
export interface TicketState {
tickets: Ticket[];
search: string;
users: User[];
loading: boolean;
error: unknown;
}
const initialState: TicketState = {
tickets: [],
search: '',
users: [],
loading: false,
error: '',
};
@Injectable()
export class TicketStore
extends ComponentStore<TicketState>
implements OnStoreInit, OnStateInit
{
readonly users$ = this.select((state) => state.users);
readonly error$ = this.select((state) => state.error);
readonly loading$ = this.select((state) => state.loading);
private readonly ticketsInput$ = this.select((state) => state.tickets);
private readonly search$ = this.select((state) => state.search);
private readonly ticketsUsers$ = this.select(
this.users$,
this.ticketsInput$,
(users, tickets) =>
users && users.length > 0
? tickets.map((ticket) => ({
...ticket,
assignee:
users.find((user) => user.id === ticket.assigneeId)?.name ??
'unassigned',
}))
: tickets
);
readonly tickets$ = this.select(
this.ticketsUsers$,
this.search$,
(tickets, search) =>
tickets.filter((t) =>
t.description.toLowerCase().includes(search.toLowerCase())
)
);
readonly vm$ = this.select(
{
tickets: this.tickets$,
users: this.users$,
loading: this.loading$,
error: this.error$,
},
{ debounce: true }
);
readonly updateAssignee = this.updater((state, ticket: Ticket) => {
const newTickets = [...state.tickets];
const index = newTickets.findIndex((t) => t.id === ticket.id);
newTickets[index] = ticket;
return {
...state,
loading: false,
tickets: newTickets,
};
});
readonly search = this.updater((state, search: string) => ({
...state,
search,
}));
private backend = inject(BackendService);
ngrxOnStoreInit() {
this.setState(initialState);
}
ngrxOnStateInit() {
this.loadTickets();
this.loadUsers();
}
readonly loadTickets = this.effect<void>(
pipe(
tap(() => this.patchState({ loading: true, error: '' })),
mergeMap(() =>
this.backend.tickets().pipe(
tapResponse(
(tickets) =>
this.patchState({
loading: false,
tickets,
}),
(error: unknown) => this.patchState({ error, loading: false })
)
)
)
)
);
readonly loadUsers = this.effect<void>(
pipe(
tap(() => this.patchState({ loading: true, error: '' })),
mergeMap(() =>
this.backend.users().pipe(
tapResponse(
(users) =>
this.patchState({
loading: false,
users,
}),
(error: unknown) => this.patchState({ error, loading: false })
)
)
)
)
);
readonly addTicket = this.effect<string>(
pipe(
tap(() => this.patchState({ loading: true, error: '' })),
mergeMap((description) =>
this.backend.newTicket({ description }).pipe(
tapResponse(
(newTicket) =>
this.patchState((state: TicketState) => ({
loading: false,
tickets: [...state.tickets, newTicket],
})),
(error: unknown) => this.patchState({ error, loading: false })
)
)
)
)
);
readonly assignTicket = this.effect<{ userId: number; ticketId: number }>(
pipe(
tap(() => this.patchState({ loading: true, error: '' })),
mergeMap((info) =>
this.backend.assign(info.ticketId, Number(info.userId)).pipe(
tapResponse(
(newTicket) => this.updateAssignee(newTicket),
(error: unknown) => this.patchState({ error, loading: false })
)
)
)
)
);
readonly done = this.effect<number>(
pipe(
tap(() => this.patchState({ loading: true, error: '' })),
mergeMap((ticketId) =>
this.backend.complete(ticketId, true).pipe(
tapResponse(
(newTicket) => this.updateAssignee(newTicket),
(error: unknown) => this.patchState({ error, loading: false })
)
)
)
)
);
}

View File

@@ -0,0 +1,59 @@
import { NgIf } from '@angular/common';
import { Component, EventEmitter, Input, Output } from '@angular/core';
import {
FormControl,
FormGroup,
ReactiveFormsModule,
Validators,
} from '@angular/forms';
import { MatButtonModule } from '@angular/material/button';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatInputModule } from '@angular/material/input';
@Component({
selector: 'app-add',
standalone: true,
imports: [
ReactiveFormsModule,
MatFormFieldModule,
MatInputModule,
MatButtonModule,
NgIf,
],
template: ` <form [formGroup]="form" #ngForm="ngForm" (ngSubmit)="submit()">
<mat-form-field class="example-full-width" appearance="fill">
<mat-label>Description</mat-label>
<input
type="text"
matInput
formControlName="description"
placeholder="My new task" />
<mat-error *ngIf="form.controls.description.hasError('required')">
Description is <strong>required</strong>
</mat-error>
</mat-form-field>
<button
class="ml-4"
mat-flat-button
color="primary"
type="submit"
[disabled]="loading">
Add new Ticket
</button>
</form>`,
})
export class AddComponent {
@Input() loading = false;
@Output() addTicket = new EventEmitter<string>();
form = new FormGroup({
description: new FormControl(null, Validators.required),
});
submit() {
if (this.form.valid) {
this.addTicket.emit(this.form.value.description ?? '');
}
}
}

View File

@@ -0,0 +1,41 @@
const USERS = [
{ id: 1, name: 'titi' },
{ id: 2, name: 'George' },
];
const TICKET_NOT_ASSIGNED = {
id: 0,
description: 'Install a monitor arm',
assignee: 'unassigned',
completed: false,
};
const TICKET_ASSIGNED = {
id: 1,
description: 'Install a monitor arm',
assignee: 'titi',
completed: false,
};
describe('RowComponent', () => {
describe('Given an unassigned ticket', () => {
describe('When we assign it to titi', () => {
it('Then assign event is emitted with ticketId 0 and userId 1', async () => {
//
});
});
});
describe('Given an assigned ticket', () => {
describe('When we click the done button', () => {
it('Then closeTicket event is emitted with ticketId 1 ', async () => {
//
});
});
});
describe('When clicking on ticket', () => {
it('Then navigation should be triggered with url detail/0', async () => {
//
});
});
});

View File

@@ -0,0 +1,84 @@
import { NgFor } from '@angular/common';
import { Component, EventEmitter, Input, Output } from '@angular/core';
import { FormControl, FormGroup, ReactiveFormsModule } from '@angular/forms';
import { MatButtonModule } from '@angular/material/button';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatInputModule } from '@angular/material/input';
import { MatSelectModule } from '@angular/material/select';
import { RouterLink } from '@angular/router';
import { Ticket, TicketUser, User } from '../../backend.service';
@Component({
selector: 'app-row',
standalone: true,
imports: [
RouterLink,
ReactiveFormsModule,
MatFormFieldModule,
MatInputModule,
MatButtonModule,
MatSelectModule,
NgFor,
],
template: `
<li
class="flex-grow flex items-center gap-5 justify-between"
[class.bg-green-200]="ticket.completed">
<button [routerLink]="['/detail', ticket.id]" class="flex flex-col gap-2">
<div><span class="font-bold">Ticket:</span> {{ ticket.id }}</div>
<div>
<span class="font-bold">Description:</span> {{ ticket.description }}
</div>
<div>
<span class="font-bold">Assignee:</span> {{ $any(ticket).assignee }}
</div>
<div><span class="font-bold">Done:</span> {{ ticket.completed }}</div>
</button>
<div class="flex flex-col">
<form
[formGroup]="form"
#ngForm="ngForm"
(ngSubmit)="submit()"
class="flex justify-center items-center gap-4">
<mat-form-field appearance="fill">
<mat-label>Assign to</mat-label>
<mat-select formControlName="assignee">
<mat-option *ngFor="let user of users" [value]="user.id">{{
user.name
}}</mat-option>
</mat-select>
</mat-form-field>
<button mat-flat-button color="primary" type="submit">Assign</button>
</form>
<button
(click)="closeTicket.emit(ticket.id)"
mat-flat-button
color="primary"
type="button">
Done
</button>
</div>
</li>
`,
host: {
class: 'p-4 border border-blue-500 rounded flex',
},
})
export class RowComponent {
@Input() ticket!: TicketUser | Ticket;
@Input() users!: User[];
@Output() assign = new EventEmitter<{ userId: number; ticketId: number }>();
@Output() closeTicket = new EventEmitter<number>();
form = new FormGroup({
assignee: new FormControl(0, { nonNullable: true }),
});
submit() {
this.assign.emit({
ticketId: this.ticket.id,
userId: this.form.getRawValue().assignee,
});
}
}

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>TestingTodosList</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 { appConfig } from './app/app.config';
import { bootstrapApplication } from '@angular/platform-browser';
import { AppComponent } from './app/app.component';
bootstrapApplication(AppComponent, appConfig).catch((err) =>
console.error(err)
);

View File

@@ -0,0 +1,13 @@
@tailwind base;
@tailwind components;
@tailwind utilities;
/* You can add global styles to this file, and also import other style files */
html,
body {
height: 100%;
}
body {
margin: 0;
font-family: Roboto, 'Helvetica Neue', sans-serif;
}

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,15 @@
{
"extends": "./tsconfig.json",
"compilerOptions": {
"outDir": "../../../dist/out-tsc",
"module": "commonjs",
"types": ["jest", "node", "@testing-library/jest-dom"]
},
"files": ["src/test-setup.ts"],
"include": [
"jest.config.ts",
"src/**/*.test.ts",
"src/**/*.spec.ts",
"src/**/*.d.ts"
]
}