Do arrow functions come highly recommended in Jasmine testing scenarios?

According to the mocha documentation, it is recommended to avoid using arrow functions.

Does this same recommendation apply to Jasmine? I could not find any information on this topic in the Jasmine documentation.

Answer №1

Don't miss out on this incredibly interesting article:

Here is a quote to ponder:

The groundbreaking approach

When running tests (and their beforeEach/afterEach hooks), jasmine assigns an empty object as the receiver of each function by default. This object, known as userContext in Jasmine's source code, can have properties added to it and is reset at the end of each test. To address our challenges, we shifted towards assigning variables to this object rather than declaring them within describe blocks and then assigning them values. Therefore, our original code transformed into something like this:

describe('views.Card', function() {
  'use strict';

  beforeEach(function() {
    this.model = {};
    this.view = new CardView(this.model);
  });

  describe('.render', function() {
    beforeEach(function() {
      this.model.title = 'An Article';
      this.view.render();
    });

    it('creates a "cardTitle" h3 element set to the model\'s title', function() {
      expect(this.view.$el.find('.cardTitle')).toContainText(this.model.title);
    });

So, what does this mean? Should arrow functions be used with jasmine?

The answer is - continue using arrow functions in your code, except for this particular combination.

// could be arrow
describe("ListModel -", () =>
{
    // local context description
    interface IMyTestContext
    {
        items?: Heroe[];
        ...
    }
    // could be arrow
    describe("Test items ", () =>
    {
        // NOT AN ARROW - benefit from Jasmine context passed as 'this'
        beforeEach(function()
        {
            var ctx: IMyTestContext = this.TestContext = {}; 
            // TODO do some defaults with context
            ...
        });

        // NOT AN ARROW - benefit from Jasmine context passed as 'this'
        it("should ...", function()
        {
            var ctx: IMyTestContext = this.TestContext;
            // TODO ... test expectations
        ...

Hence, beforeEach() and it() should NOT use arrows to make use of the Jasmine context accessible via this

We can also implement a global beforeEach() call

import * as something from "...";

beforeEach(function()
{
    this.TestContext = {};
});

Now, the context is readily available to us without having to recreate it:

describe("Track Changed items ", () =>
{
    // NOT AN ARROW - benefit from Jasmine context passed as 'this'
    beforeEach(function()
    {                                              // created by global beforeEach above
        var ctx: IMyTestContext = this.TestContext;//  = {}; 

Indeed, it's truly remarkable that if a test runner detects a global beforeEach()... it will execute it before every test... isn't that awesome?

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Encountering an error in Chrome where the property 'command' is undefined

Currently utilizing typescript and encountered an error in the chrome console: Error found in event handler for (unknown): TypeError: Unable to access property 'command' as it is undefined at chrome-extension://somethingsomethingsometh ...

Style the date using moment

All languages had a question like this except for JavaScript. I am trying to determine, based on the variable "day," whether it represents today, tomorrow, or any other day. ...

The changes made to the path property in tsconfig.json are not being registered

A troublesome block of imports has surfaced, as shown in this image: https://i.sstatic.net/lRwK5.png Below is my current configuration in tsconfig.json : { "compilerOptions": { "target": "es5" /* Specify ECMAScript targ ...

Issue with package: Unable to locate the module specified as './artifacts/index.win32-ia32-msvc.node'

I am encountering an issue while using Parcel for the first time. When I execute npx parcel .\app\index.html, I receive the following error: Error: Module not found './artifacts/index.win32-ia32-msvc.node' Require stack: - C:\Users ...

I am having trouble getting debugging with source maps to work in VSCode and Browserify

I'm currently experiencing an issue with setting breakpoints in Chrome using VSCode, especially when working with TypeScript and Browserify. Oddly enough, if I open Chrome separately and manually refresh the page, the source maps load correctly and I ...

Expanding the width of an MUI Button smoothly using transitions

I am currently working on a custom ToggleButton that changes its text based on certain state changes. However, I am facing an issue where the width of the button abruptly grows when the text changes. How can I smoothly transition this change in width? Bel ...

Determining the type of a single deconstructed variable from an object

My useForm hook is designed to take an object and return several useful functions back, including that object as a state. However, due to TypeScript limitations, the specific type from the initial object cannot be returned because useForm accepts dynamic o ...

What could be causing variations in the performance of my Speech Recognition code each time I run it?

Check out my code snippet: export class voiceRecognition { constructor() { } public startVoiceRecognition() { const recognition = new webkitSpeechRecognition(); recognition.continuous = false; recognition.interimresults = false; recogn ...

An Angular module downloaded from npm seems to be lacking the required @NgModule declaration

There seems to be a missing @NgModule and @Directive declarations in an NPM module, even though they exist in the source code on Github. This is causing an issue with importing a directive for databinding from an HTML attribute. I am attempting to utilize ...

Angular2 ERROR: Unhandled Promise Rejection: Cannot find a matching route:

I'm facing an issue with my Angular2 application while utilizing the router.navigateByUrl method. Within my component, there is a function named goToRoute, structured as follows: router.goToRoute(route:string, event?:Event):void { if (event) ...

Is it necessary for me to be familiar with AngularJS in order to redesign an app for Angular 2+

I'm curious - when rewriting an application from AngularJS to Angular 2+, do you need to be familiar with both, or is knowing just Angular 2+ sufficient? ...

Hover effect on Angular Material Stepper

Is there a way to apply CSS styles to a specific step (Angular material stepper) when hovering over it? I have attempted to set the styles on the elements .mat-step-header and mat-step, as well as applying a custom CSS class, but so far nothing has seeme ...

Issues with the md-radio-button not functioning properly in Angular 2

I'm in need of two radio buttons to choose between two options. Here's the code I'm using: <md-radio-button [value]=true [(ngModel)]="carSelected" name="carOption">Car</md-radio-button> <md-radio-button [value]=false [(ngMode ...

Strategies for handling asynchronous requests and effectively presenting the retrieved data

On my HTML page, I have a badge component that shows the number of unread messages. Here is the HTML code: <button class="font" mat-menu-item routerLink="/message"> <mat-icon>notifications</mat-icon> <span [matBadgeHidden]="newM ...

Adding Components Dynamically to Angular Parent Dashboard: A Step-by-Step Guide

I have a dynamic dashboard of cards that I created using the ng generate @angular/material:material-dashboard command. The cards in the dashboard are structured like this: <div class="grid-container"> <h1 class="mat-h1">Dashboard</h1> ...

How do I select all checkboxes in TypeScript when I only click on one of them?

I'm currently working with a list of checkboxes in my HTML code: <div class="col-sm-12" *ngIf="ControllerModel"> <div *ngFor="let controller of ControllerModel" class="panel col-md-6 col-lg-6 col-xs-6"> <div class="panel-heading" ...

Exploring TypeScript Object Properties in Angular 2

How can I extract and display the ID and title of the Hero object below? The structure of the Hero interface is based on a Firebase JSON response. hero.component.ts import {Component, Input} from 'angular2/core'; import {Hero} from '../mod ...

What is the best way to employ document.addEventListener in TypeScript?

I am currently learning Ionic v2 and I am using document.addEventListener, but I am encountering errors as shown below: > [11:10:21] ionic-app-scripts 0.0.47 [11:10:21] build dev started ... [11:10:21] clean started ... [11:10:21] clean finished in ...

Typescript causing undefined React Router match issue

Currently, I am working on a basic eCommerce Proof of Concept using react and TypeScript. Unfortunately, I am facing an issue where I am unable to pass props to a product detail page or access the match containing the params. This is how my Routes pages a ...

Strategies for Safely Assigning Firestore Data to an Object Without Losing Null Values

I am dealing with a class setup as follows: export class Car{ color=''; topSpeed=0; wheels = 4; } Within my Firestore database, there exists a document titled "car" with values: color:red topSpeed:230 (note that the 'wheels&a ...