How to setup JEST with ANGULAR incl working sample

unit testing

I wanted to make a whole story on this, but i’d rather try make this document as helpful and to the point as possible, hope this helps you setup jest in your Angular project.


import jest setup that is found in the jest-preset-angular.
This will be in your test.ts file

// add to test.ts file
import 'jest-preset-angular/setup-jest';

Add the following jest packages the the package.json

 // package.json file
 
 // update your test script to
    "test": "jest",
 
 // Packages to add to devDependencies
    "jest": "^27.3.1",
    "jest-preset-angular": "^10.0.1"

After adding the jest packages be sure to run npm install, you can also remove the karma packages to keep things tidy.
In the project’s tsconfig.json add the following to your compilerOptions object:

// add the following in your tsconfig.json
...,
  "angularCompilerOptions": {
    "fullTemplateTypeCheck": true,
    "strictInjectionParameters": true
  }

Run the following command, this will help transcript jest to typescript seeing that jest is JavaScript and will need to work with type script.

npm i ts-jest

Create a jest.config.js file in the base of your project ‘src/jest.config.js’

const { pathsToModuleNameMapper } = require('ts-jest');
const { compilerOptions } = require('./tsconfig.json');

module.exports = {
    preset: "jest-preset-angular",
    setupFilesAfterEnv: ["<rootDir>/src/test.ts"],
    testMatch: ["**/+(*.)+(spec).+(ts)"],
    moduleNameMapper: pathsToModuleNameMapper(compilerOptions.paths || {}, {prefix: "<rootDir>/"})
}

I think that that should sort you out. With regards to the different versions of Angular and Jest, and its angular preset packages, they seem to be inline with the angular version number, like my project is angular 11 and I have another using 12 and the preset 10 and up seems to cover it. I also have used it on an Angular 9 project and the jest-preset-angular version was 9.0.4

EXTRA SETUP NOTE FOR JEST
I had to added the Jest to the types in the tsconfig.spec.json, so that my unit test files have access to jest.

Sample project with Jest setup already:
sample-project

Angular active router link

merryxmas lego

Merry Xmas and there isn’t a TLDR on this post but there is an angular 10 git project repo below! stay safe wear a mask properly and take care of yourselves.


I assure you that this is easier than you think it is. Firstly you’ll need to add the active rout class to your css or scss,

I’ll be honest I went a bit overboard with the styles but ya its for demonstrative purposes I swear

Side Note I would love some feedback on if my image snippets are helpful or readable.
You want to place some code in your style sheets for the active state style.


.nav ul li a.active {
    font-weight: 600;
    background-color:blue;
    color: white;
}

// or just simply
.active {
     font-weight: 600;
     color: white;
}

You want to import this active router functionality into this project so go to your project modules. This snippet is in the context of my project by the way so just note the RouterModule.

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { HomeComponent } from './components/home/home.component';
import { PageOneComponent } from './components/page-one/page-one.component';
import { PageTwoComponent } from './components/page-two/page-two.component';
import { PageThreeComponent } from './components/page-three/page-three.component';
import { RouterModule, Routes } from '@angular/router';
import { NavbarComponent } from './components/navbar/navbar.component';

const routes: Routes = [
  { path: 'home', component: HomeComponent },
  { path: 'page-one', component: PageOneComponent },
  { path: 'page-two', component: PageTwoComponent },
  { path: 'page-three', component: PageThreeComponent },
  { path: '**', component: HomeComponent }

]; // sets up routes constant where you define your routes


@NgModule({
  declarations: [
    AppComponent,
    HomeComponent,
    PageOneComponent,
    PageTwoComponent,
    PageThreeComponent,
    NavbarComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    RouterModule.forRoot(routes)
  ],
  exports: [RouterModule],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }


Note the export and imports above, be sure to place it in the correct style sheet. From there active your navigation styles tags like so.

<nav class="nav">
    <ul>
      <li><a routerLink="/home" routerLinkActive="active">home </a></li>
      <li><a routerLink="/page-one" [routerLinkActive]="['active']">page-one</a></li>
      <li><a routerLink="/page-two" [routerLinkActive]="['active']">page-two</a></li>
      <li><a routerLink="/page-three" [routerLinkActive]="['active']">page-three</a></li>
    </ul>
  </nav>

Npm install and make sure nothing is missing and you should be well on your way with the active styles triggering per active link match. For a working example checkout my github project.

For a deeper implementation referencing parents and ancestors please be sure to take a look at the following post.

JavaScript Keypresses keyup keydown keypress

As Always I try to make my blog cater for peeps that are just looking for concise answers, so if you scroll down there is a TL DR section below. If you are curious of my thoughts then keep reading.

My knowledge of keypresses consisted of the brief summary of “you press a key and you can make something happen”. Turns out there is a bit more to it.

Keypresses have three different trigger points. I’m going to put my naive understanding of them first, then what MDN says cause that is the best source of truth out there in my opinion. I also used StackOverflow.

First you have keydown

My understanding of a Keydown is the action of when the button is pressed, so as the key is pressed down you can set an action or trigger something from that point.

Unlike the keypress event, the keydown event is fired for all keys, regardless of whether they produce a character value.

from MDN

To sum keydown: Keydown will trigger for all keys pressed(odd ones being ctrl, shift. delete..etc). If you press any key thats a keydown.

Second you have keyup

My understanding of a key up is the “release” action of the keydown action. So you can set an action upon lifting your key from a pressed state.

The keydown and keyup events provide a code indicating which key is pressed, while keypress indicates which character was entered. For example, a lowercase “a” will be reported as 65 by keydown and keyup, but as 97 by keypress. An uppercase “A” is reported as 65 by all events.

from MDN

To sum up keyup:. It trigger upon the release of a pressed key. Don’t worry MDN can be intimidating at times. It took me a while, but they are saying a keyup will trigger with a value of what key was pressed. Also, I think MDN has already moved on tooo..

Thirdly the keypress

My understanding: Keypress is the full action of just typing a key. so hit a key and let go and you have yourself a keypress buddy.

The keypress event is fired when a key that produces a character value is pressed down. Examples of keys that produce a character value are alphabetic, numeric, and punctuation keys. Examples of keys that don’t produce a character value are modifier keys such as Alt
, Shift
, Ctrl
, or Meta

From MDN

Ok, so my understanding of a keypress was a bit off. It appears to be including all chars that set a value and not other keys like shift, control, alt…etc that don’t produce a character. According to MDN it appears that the keypress is deprecated so you would just need to be aware of that when using keypress.

I never in my life thought that someone could complicate a key press, but here we are 2020 virus is out. Try to stay inside guys ok.

TL DR

The onKeyDown event is triggered when the user presses a key.
The onKeyUp event is triggered when the user releases a key.
The onKeyPress event is triggered when the user presses & releases a key (onKeyDown followed by onKeyUp).

from stackoverflow

In my defence I’m not as technical as MDN, my theory was around more towards what the stackoverflow post said.

I’ll leave you with that guys I really hope that this helps you out and helps you know that there is a bit more to a keypress than meets the eye.

On a side note. I got some positive comments on my previous post. Thanks so much for the support I’ll continue posting my findings and sharing the knowledge to help myself and others. I was so chuffed in fact i made a live sample of some javaScript and keypresses right here enjoy.

[Sample] Angular hitting API with Service

If you want the sample main steps scroll to the “TO THE POINT” part of this article thanks. If you all good keep reading.

So this lock out isolation thing has been quite challenging for everyone and I feel your pain. I was working on an angular portfolio…but its been mainly css when trying to cater for mobile view and tablet view…so I want to take a break from the css and get into interacting with an API

If you don’t know what an API is…this wont cover the fundamentals sadly, it’ll be a working example of an api request. As for now we are Focusing on Angular working with APIs using services.

There are many free open API sites the one i came across apifootball.com where upon registering they’ll provide you with an API key (you’ll need to keep this safe and secure) From my experience most of the free apis require a registration.

We have an api and an api key, now you want to check and see if we can make a call of some sort and log a response. A great API tool is postman. Basically setup the API call to your liking and it allows you to see and track the response and what not, look its great.

ok so that is the long of it. Now i’m going to try to keep it as short as possible. Yes that does say “overal_league_payed” learned that the hard way.

TO THE POINT HOW TO SETUP TO HIT AN API

Using the angular cli we can just enter the following command in the terminal

// short hand
ng g s serviceName
// full on
ng generate service serviceName

The command will generate a service for you in your solution. Basic boiler plate.

Right now you know your API is working. Let’s make that service in our angular app give that API a call and see if we can get their response.

We need RXJS thats right that beast that does magic with Observables (high level comparison of observables vs promises.).

npm i rxjs

Make sure that you are using HttpClient for the http calls.
I normally use the below structure for api calls. Adding variable for base urls and other things that are constant like my apiKey this is just personal preference.

I was advised that when it comes to services, make sure they only deliver the data keep that part clean. Now moving along to the app.component we’ll need to create a function that hits that service and the getLeagueStand and subscribe to the response and then extract the data you want. Make sure you return the url.

And ALSO do not forget to import your service and the httpClient module to your app.module file like so…I can’t believe I forgot to add this guy.



As you can see in the code above we subscribing to the data and then setting out its values to variables. Here is a repo to a working sample. You’ll need to add your own apikey though.

How do I add a Fancy github ribbon, this is the fastest way I know

If you want the story version you can continue reading, if you want to solution i found then skip to the bottom of the page. 😉

I was recently updating my rock paper scissors game to work on mobile sized screens.

The mobile screen adjustments took me some time, because I learned only after i finishing my css, making all my styles for desktop use only. I found out that most people will browse this link via their mobile phones and so my beta was a disaster in mobile views… but i digress.

Anthony Marques 2019

Aaaand when I was done, I was very proud of the results. I even figured lets make this public, so i shared my work of art on Reddit waiting for the likes to come rolling in.

BUT i got flagged for showing off by the mods…which they were more or less correct. I wanted to show the world what i have done, but then they insisted of the following rules:

Only one thing came into mind, i need to add a fork me on github ribbon, it sounded like a sure fire way for my rps game to be accepted by the JavaScript sub. I needed to know how to do this.

Then i came across this little site. This was basically the answer to what I was looking for. I did try to find other ways of implementing it, but i needed a quick solution

<a href="">
<img style="position: absolute; top: 0; right: 0; border: 0;" src="https://s3.amazonaws.com/github/ribbons/forkme_right_darkblue_121621.png" alt="Fork me on GitHub">
</a>

Just update that href with your github site and you are good to go, enjoy forking and sharing.

Here is the end result!

rps game mobile view

Here is a link to the ROCK PAPER SCISSORS game i made your avator which is me takes on real damage. feel free to take a looky