feat(test): add challenge 18 and 19 avout testing

This commit is contained in:
thomas
2023-04-08 14:18:49 +02:00
parent 95e0f6b5f8
commit b52ff0697b
52 changed files with 2126 additions and 202 deletions

View File

@@ -0,0 +1,19 @@
{
"extends": ["../../.eslintrc.json"],
"ignorePatterns": ["!**/*"],
"overrides": [
{
"files": ["*.ts"],
"rules": {},
"extends": [
"plugin:@nrwl/nx/angular",
"plugin:@angular-eslint/template/process-inline-templates"
]
},
{
"files": ["*.html"],
"extends": ["plugin:@nrwl/nx/angular-template"],
"rules": {}
}
]
}

View File

@@ -0,0 +1,36 @@
<h1>Nested component testing</h1>
> Author: Thomas Laforge
### Statement:
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-nested`.
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-nested`. 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-nested` 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 install
4. `npx nx serve testing-nested` to play with the application
5. `npx nx test testing-nested` to test your application with Testing Library
6. `npx nx component-test testing-nested --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:18** that I will review and other dev can review.
<a href="https://github.com/tomalaforge/angular-challenges/pulls?q=label%3A18+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%3A18+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 '@nrwl/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,13 @@
<!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-nested 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,17 @@
{
"extends": "../tsconfig.json",
"compilerOptions": {
"outDir": "../../../dist/out-tsc",
"module": "commonjs",
"types": ["cypress", "node"]
},
"include": [
"support/**/*.ts",
"../cypress.config.ts",
"../**/*.cy.ts",
"../**/*.cy.tsx",
"../**/*.cy.js",
"../**/*.cy.jsx",
"../**/*.d.ts"
]
}

View File

@@ -0,0 +1,22 @@
/* eslint-disable */
export default {
displayName: 'testing-nested',
preset: '../../jest.preset.js',
setupFilesAfterEnv: ['<rootDir>/src/test-setup.ts'],
coverageDirectory: '../../coverage/apps/testing-nested',
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,105 @@
{
"name": "testing-nested",
"$schema": "../node_modules/nx/schemas/project-schema.json",
"projectType": "application",
"sourceRoot": "apps/testing-nested/src",
"prefix": "app",
"targets": {
"build": {
"executor": "@angular-devkit/build-angular:browser",
"outputs": ["{options.outputPath}"],
"options": {
"outputPath": "dist/apps/testing-nested",
"index": "apps/testing-nested/src/index.html",
"main": "apps/testing-nested/src/main.ts",
"polyfills": ["zone.js"],
"tsConfig": "apps/testing-nested/tsconfig.app.json",
"inlineStyleLanguage": "scss",
"assets": [
"apps/testing-nested/src/favicon.ico",
"apps/testing-nested/src/assets"
],
"styles": ["apps/testing-nested/src/styles.scss"],
"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": "testing-nested:build:production"
},
"development": {
"browserTarget": "testing-nested:build:development"
}
},
"defaultConfiguration": "development"
},
"extract-i18n": {
"executor": "@angular-devkit/build-angular:extract-i18n",
"options": {
"browserTarget": "testing-nested:build"
}
},
"lint": {
"executor": "@nrwl/linter:eslint",
"outputs": ["{options.outputFile}"],
"options": {
"lintFilePatterns": [
"apps/testing-nested/**/*.ts",
"apps/testing-nested/**/*.html"
]
}
},
"test": {
"executor": "@nrwl/jest:jest",
"outputs": ["{workspaceRoot}/coverage/{projectRoot}"],
"options": {
"jestConfig": "apps/testing-nested/jest.config.ts",
"passWithNoTests": true
},
"configurations": {
"ci": {
"ci": true,
"codeCoverage": true
}
}
},
"component-test": {
"executor": "@nrwl/cypress:cypress",
"options": {
"cypressConfig": "apps/testing-nested/cypress.config.ts",
"testingType": "component",
"skipServe": true,
"devServerTarget": "testing-nested:build"
}
}
},
"tags": []
}

View File

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

View File

@@ -0,0 +1,15 @@
import { ChildComponent } from './child.component';
describe(ChildComponent.name, () => {
const setup = () => {
cy.mount(ChildComponent);
};
test('add Good title and send request title with no error', () => {
setup();
});
test('fail validating title because no title were typed', () => {
setup();
});
});

View File

@@ -0,0 +1,12 @@
import { render } from '@testing-library/angular';
import { ChildComponent } from './child.component';
describe('ChildComponent', () => {
test('add Good title and send request title with no error', async () => {
await render(ChildComponent);
});
test('fail validating title because no title were typed', async () => {
await render(ChildComponent);
});
});

View File

@@ -0,0 +1,86 @@
import { NgIf } from '@angular/common';
import {
ChangeDetectionStrategy,
Component,
EventEmitter,
Input,
Output,
inject,
} from '@angular/core';
import { FormControl, ReactiveFormsModule } from '@angular/forms';
import { HttpService } from './http.service';
@Component({
selector: 'app-input',
standalone: true,
imports: [ReactiveFormsModule],
template: ` <input type="text" [formControl]="title" /> `,
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class InputComponent {
title = new FormControl('', { nonNullable: true });
}
@Component({
selector: 'result',
standalone: true,
template: ` <p>Title is {{ title }}</p> `,
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class ResultComponent {
@Input() title = '';
}
@Component({
selector: 'app-button',
standalone: true,
template: `<button (click)="validate.emit()">Validate</button>`,
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class ButtonComponent {
@Output() validate = new EventEmitter();
}
@Component({
selector: 'app-error',
standalone: true,
template: `<p>Title is required !!!</p>`,
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class ErrorComponent {
@Output() validate = new EventEmitter();
}
@Component({
selector: 'app-child',
standalone: true,
imports: [
ResultComponent,
ButtonComponent,
InputComponent,
ErrorComponent,
NgIf,
],
template: `
<app-input #input></app-input>
<result [title]="input.title.value"></result>
<app-button (validate)="submit(input.title.value)"></app-button>
<app-error *ngIf="showError"></app-error>
`,
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class ChildComponent {
http = inject(HttpService);
showError = false;
submit(title: string) {
this.showError = false;
if (title === '') {
this.showError = true;
return;
}
this.http.sendTitle(title);
}
}

View File

@@ -0,0 +1,8 @@
import { Injectable } from '@angular/core';
@Injectable({ providedIn: 'root' })
export class HttpService {
sendTitle(title: string) {
console.log(`${title} has been sent !!!`);
}
}

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

View File

@@ -0,0 +1 @@
/* You can add global styles to this file, and also import other style files */

View File

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

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.cy.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"
]
}