Is there a marble experiment that will alter its results when a function is executed?

Within Angular 8, there exists a service that contains a readonly Observable property. This property is created from a BehaviorSubject<string> which holds a string describing the current state of the service. Additionally, the service includes methods to modify its state.

export class StateService {
  private _state = new BehaviorSubject<string>('before');

  readonly state$ = this._state.asObservable();

  constructor () { }

  begin() { this._state.next('during'); }

  finish() { this._state.next('after'); }

  reset() { this._state.next('before'); }
}

The goal is to conduct marble tests within the Jasmine test suite to effectively evaluate the observable value upon state changes.

let scheduler: TestScheduler;

beforeEach(() => {
  scheduler = new TestScheduler((actual, expected) => {
    expect(actual).toEqual(expected);
  });
});

it('should flow states correctly', () => {
  scheduler.run(({expectObservable, flush}) => {
    const svc = setupSvc(); //Function call within the suite to initialize the StateService

    svc.begin();
    svc.finish();
    svc.reset();

    flush();

    expectObservable(svc.state$).toBe('a-b-c-d', {
      a: 'before',
      b: 'during',
      c: 'after',
      d: 'before'
    });
  });
});

Various attempts have been made by invoking begin, finish, reset, and utilizing the scheduler's flush helper. However, the expected outcome consistently displays only the initial value (represented by the a marble) without any further changes.

What crucial element am I overlooking in order to successfully achieve this testing approach? Alternatively, could marbles not be the most appropriate method for testing this scenario?

Answer №1

Utilizing a cold observable generated through the test helper appears to be effective:

it('should correctly handle state transitions', () => {
  scheduler.run(({ expectObservable, cold }) => {
    const svc = new StateService();

    cold('--a-b-c', {
      a: 'start',
      b: 'end',
      c: 'restart'        
    }).subscribe(action => {
      svc[action]();
    })

    expectObservable(svc.state$).toBe('a-b-c-d', {
      a: 'pre-start',
      b: 'in-progress',
      c: 'post-end',
      d: 'pre-start'
    });
  });
});

Check out the code on StackBlitz

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

The data type 'string | number | boolean' cannot be assigned to type 'undefined'. Specifically, the type 'string' is incompatible with type 'undefined'. Error code: ts(2322)

When attempting to create a partial object with specific fields from a full object that meet certain criteria, I encountered a TypeScript error message. To better explain this issue, I designed a test module to showcase the concept/problem without using ac ...

Returning a value with an `any` type without proper validation.eslint@typescript-eslint/no-unsafe-return

I am currently working on a project using Vue and TypeScript, and I am encountering an issue with returning a function while attempting to validate my form. Below are the errors I am facing: Element implicitly has an 'any' type because expression ...

Which material design framework would be more suitable for my Angular 6 application - Angular Material or Bootstrap Material?

When starting my new Angular 6 application with Material Design, the big question arose: which material library should I use? Angular Material (https://material.angular.io/) Material Design for Bootstrap () Another option is the Bootstrap Material libr ...

Encountering an issue with testing CKEditor in Jest

Testing my project configured with vite (Typescript) and using jest showed an error related to ckeditor. The error is displayed as follows: [![enter image description here][1]][1] The contents of package.json: { "name": "test-project" ...

Having difficulties creating a new instance of a class

I'm encountering an issue with this TypeScript code import Conf = require('conf'); const config = new Conf(); The Problem: the expression is not constructable and the imported module lacks construct signatures It's puzzling because th ...

I'm currently learning about things that never change and struggling to grasp their meaning

I'm currently delving into the world of immutable.js record and trying to wrap my head around it. However, this particular piece of code is really throwing me for a loop. Here's my Question: I understand [import, export,const], but what ex ...

Issue: Unable to find the last element using the function findLast in Jest test

While working on a test using jest in Angular, I encountered the following error: Error: TypeError: columnDefs.findLast is not a function The method I am attempting to test is as follows: onKeyDown(key: any) { const columnDefs = this.params.columnApi ...

Transform an array of Boolean values into a string array containing only the values that are true

Suppose we have an object like the following: likedFoods:{ pizza:true, pasta:false, steak:true, salad:false } We want to filter out the false values and convert it into a string array as shown below: compiledLikedFoods = ["pizza", "steak"] Is t ...

Developing an object using class and generic features in Typescript

I am currently working on creating a function or method that can generate sorting options from an array. One example is when using Mikro-ORM, where there is a type called FindOptions<T> that can be filled with the desired sorting order for database q ...

Receiving the [object HTMLInputElement] on the screen rather than a numerical value

I have an input box where a user can enter a number. When they click a button, I want that number to be displayed on the page. However, instead of seeing the number, I am getting the output as [object HTMLInputElement]. Below is my TypeScript code: let qu ...

Is it possible to retrieve and utilize multiple Enum values in Typescript?

Combine enum values to retrieve corresponding enum strings. Consider the following scenario: enum EnumDays { NONE = 0, SUN = 1, MON = 2, TUE = 4, WED = 8, THU = 16, FRI = 32, SAT = 64, ALL = 127 } If I pass a value o ...

Steps to deploy an ASP.NET Angular application that has been published

I am working on an Angular application that is being managed by an ASP.NET application following a similar setup as described in this tutorial. During development, I usually use the command dotnet run from within the ASP.NET project directory to build both ...

How can we create a unique type in Typescript for a callback that is void of any return value?

When it comes to safe callbacks, the ideal scenario is for the function to return either undefined or nothing at all. Let's test this with the following scenarios: declare const fn1: (cb: () => void) => void; fn1(() => '123'); // ...

How can I effectively organize an Angular2 component library for optimal efficiency?

Looking to develop an Angular2 datepicker component with the intention of releasing it and using it in multiple projects. Wondering about the best way to structure the project for this specific purpose compared to a typical Angular2 project created with an ...

Displaying all notifications while using parameters in TypeScript

I am trying to display all of my notifications in HTML. The value is returned in res = response.json();, but my website only shows one notification, similar to the example in Let's start with this code: public eventsbyserial(id: string): Observab ...

Next.js Issue: Invariant error - page not correctly generated

I encountered a recurring error while attempting to build my project. Strangely, everything runs smoothly during development, but as soon as the build process is initiated, the following error presents itself: next build ▲ Next.js 14.1.0 - Environm ...

Generating Graphql types for React using graphql-codegen when Apollo Server is in production mode: A step-by-step guide

Everything functions perfectly when backend mode is set to NODE_ENV: development, but in production mode I encounter an error with graphql-codegen: Error on local web server: Apollo Server does not allow GraphQL introspection, but the query contains _sc ...

The element called 'userForm' cannot be found within the 'RootComponent' instance

My Angular component class is facing a strange issue when I try to compile it using npm start. The first time, it fails to compile and throws the error: ERROR in src/app/root/root.component.ts(14,12): error TS2339: Property 'userForm' does not e ...

Using TypeScript to test a Vue3 component that includes a slot with Cypress

I'm currently facing challenges setting up a new project. The technologies I am using include Vue3, TypeScript, and Cypress. It seems like the problem lies within the TypeScript configuration. Below is a Minimal Working Example (MWE) of my setup. Any ...

How can I display a header from one page on a different page in Ionic?

Using Ionic 3 on my Home Page, I have the following code snippet. Whenever the searchMore button is clicked, it leads to a new page. The objective is to display "Cook With What is in My Pantry" from the h5 tag on the new page. <ion-grid> <io ...