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

Retrieve the component when there is a change in the variable in Angular versions greater than 4

When invoking the ngx-ebar-treemo component in my main component, I use the following syntax: <ngx-ebar-treemo *ngIf="type=='Bar' && graphic" type1="{{type1}}" type2="{{type2}}"></ngx-ebar-treemo> I need to call this compone ...

Use rowSelected to set the initial selected rows in an Angular Kendo UI grid

Within my Kendo UI Grid, the ability to select individual rows is made possible by clicking a checkbox that adds them to an array. However, my goal is to initially set selected rows based on whether or not the dataItem for each row exists in a specified ar ...

retrieving information from an array nested within a JSON object in an Angular application

I am struggling to retrieve two specific values from a JSON object. The content of the JSON is as follows: [ { "type":"session_start", "properties":[ { "property":"activity&q ...

What is the best way to establish a connection between the Angular front end and a remote MySQL server using a

I am currently working on a local Angular front-end login page that requires user authentication. The users' data is stored on a remote server, and I need to connect to a MySQL database on the server using a PHP API for authentication. Can someone pro ...

Angular is showing an error indicating that the property "name" is not found on an empty object

After thorough checking, I have confirmed that the property does exist with the correct key. However, it is returning an error message stating name is not a property of {}. I attempted to assign this object to an interface along with its properties but enc ...

An error was encountered while attempting to redirect in an Angular 4 project, the URL was set up for HTTPS

I've been attempting to access an Angular 4 project deployed locally on my machine through a form on an HTML page: <!DOCTYPE html> <html> <body> <form action="https://test-pubg.sohum.com:4200" target="_blank" method="post"> ...

Transform a base64 image into a blob format for transmission to the backend via a form

Is there a way to convert a base64 string image to a blob image in order to send it to the backend using a form? I've tried some solutions like this one, but they didn't work for me. function b64toBlob(b64Data, contentType='', sliceSiz ...

The password field value in an Angular form is not defined

After making some modifications to a sign-in template that worked perfectly before, I encountered an error when trying to submit the signup form. The error message reads as follows: ERROR TypeError: Cannot read property 'value' of undefined Here ...

An unexpected error has occurred in Angular 2 while referencing the service proxy with code asd:18. The error message is: (SystemJS) Unexpected token < SyntaxError: Unexpected token

Forgive me for asking what may seem like a silly question. I am a newcomer to Angular 2 and encountering some problems with the API that my app is utilizing. The consumed Web API is located within the following folder structure: - src - app - Regist ...

I'm encountering an issue trying to apply array filtering with checkboxes using React hooks and TypeScript

Help needed! I'm facing an issue while trying to filter an array based on gender using checkboxes. The functionality works fine for the male checkbox but seems to fail when clicking on the female checkbox. Below is the code snippet from my App.tsx fil ...

Error 16 occurred when attempting to ngUpgrade two different versions of Highcharts

After successfully upgrading my app to use ngUpgrade, I encountered an issue while trying to incorporate Highcharts. In the original version of the app, there was an older version of Highcharts designed for AngularJS. However, in the new hybrid app using ...

Error message: Deno package code encounters error due to the absence of 'window' definition

I am facing an issue with a npm package I imported into my Deno project. The code in the package contains a condition: if (typeof window === 'undefined') { throw new Error('Error initializing the sdk: window is undefined'); } Wheneve ...

Encountered a Next-Auth Error: Unable to fetch data, TypeError: fetch failed within

I've been struggling with a unique issue that I haven't found a solution for in any other forum. My Configuration NextJS: v13.0.3 NextAuth: v4.16.4 npm: v8.19.2 node: v18.12.1 When the Issue Arises This particular error only occurs in the pr ...

The number pipe is unable to interpret the given value, either because it is outside of the allowable range or cannot be

An error occurred while processing the specified value, it seems to be either unparsable or out of the acceptable range. Whenever I apply formatting with a pipe to a number in my object, I encounter this warning and the value fails to display. However, on ...

Typescript's implementation of AngularJs provider

After creating an Angularjs provider in typescript, I found myself wondering if there might be a more efficient way to achieve the same outcome. My current provider serves as an abstraction for a console logger, with the interface primarily designed to s ...

Newest Angular package.json

Each time I attempt to update my Angular components to the latest version, I encounter the same error. It seems like a never-ending cycle... npm ERR! code ERESOLVE npm ERR! ERESOLVE could not resolve npm ERR! npm ERR! While resolving: <a href="/cdn-cgi/ ...

``The positioning of the element does not seem to be effective with the selected [

I'm struggling to position a div using [style]. Even after following the advice from various sources, I can't seem to place the div correctly at 100,100. Could someone please review the code snippet below and point out any errors? Check out the ...

Order of Execution

I am facing an issue with the order of execution while trying to retrieve values from my WebApi for input validation. It appears that the asynchronous nature of the get operation is causing this discrepancy in execution order. I believe the asynchronous b ...

Struggling to incorporate method decorators to handle http errors in Angular?

My goal is to implement error handling for all http requests using custom decorators. Here's my current code snippet: createRecord(data: data) { return this.httpClient.post(`${this.apiURL}/record/`, data); } I am looking to refactor thes ...

Unable to retrieve multiple values from a sinon stub

I am trying to stub a method using sinon in my Typescript code with Bluebird promises. However, I'm running into an issue where only the first value I set for the stub is being returned, even though I want it to return a different value on the second ...