When an Angular service is created, its properties are not immediately configured

My current task involves testing an Angular (4.1) service that looks like this:

@Injectable()
export class JobService {
  private answerSource = new Subject<AnswerWrapper>();
  answer$ = this.answerSource.asObservable(); 

  answer(answer: AnswerWrapper) {
    this.answerSource.next(answer);
  }

I am using the following unit test to validate the service:

  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [JobService]
    });
  });

  it('should emit $answer on answer()', inject([JobService], (service: JobService) => {
    service.answer$.subscribe(val => expect(val).toEqual('test123'));
    service.answer(('test123' as any))
  }));

Despite my efforts, I encountered the error message:

Cannot read property 'subscribe' of undefined

I am puzzled by this because I believe everything should be properly set up during service creation. Any insights on why this could be happening?

Answer №1

Ensure to include this line within a constructor function

observableAnswer$ = this.answerSource.asObservable(); 

The answerSource Subject will be initialized prior to the execution of the constructor

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

Challenges arise when working with Vue 3.2 using the <script setup> tag in conjunction with TypeScript type

Hey there! I've been working with the Vue 3.2 <script setup> tag along with TypeScript. In a simple scenario, I'm aiming to display a user ID in the template. Technically, my code is functioning correctly as it shows the user ID as expect ...

Conflicting TypeScript enum types: numbers and numbers in NestJS/ExpressJS

Incorporating types into my NestJS server has been a priority. After creating a controller (a route for those who prefer Express), I attempted to define the type for params: public async getAllMessages( @Query('startDate', ValidateDate) start ...

Issue with the exported elements known as 'StatSyncFn'

My build is showing an error that I'm unable to identify the source or reason for. The error message looks like this... Error: node_modules/webpack-dev-middleware/types/index.d.ts:204:27 - error TS2694: Namespace '"fs"' has no expo ...

Unexpected output from nested loop implementation

Having some arrays, I am now trying to iterate through all tab names and exclude the values present in the exclusion list. json1 ={ "sku Brand": "abc", "strngth": "ALL", "area ...

Using CKEditor5 to Capture and Edit Key Presses

I'm currently working on capturing input from a CKEditor5 within an Angular application using TypeScript. While I am able to successfully display the CKEditor and confirm its presence through logging, I am facing difficulties in capturing the actual i ...

What is the reason behind Typescript executing the abstract class before anything else?

I'm currently facing a challenge solving an abstract class problem with Typescript. Let me explain what I am trying to accomplish. There is a class named Sword that extends Weapon. Each Weapon must have certain properties like the damage, but since e ...

Unable to set items as sticky within mat-tabs

Is there a way to make my image stick in place using the following CSS code? position: -webkit-sticky; position: sticky; top: 1px; I have tried implementing it but haven't been successful. HTML: <mat-tab-group class="user-tabs" (selectedTa ...

Transfer my testing utilities from React Router version 5 to version 6

I am currently transitioning my project to React V6 router and encountering an issue with my test utility function. Every time I run the test, all my expectations fail because jest cannot locate the object. Has anyone faced this error during a similar migr ...

Excluding a common attribute from a combined type of objects can lead to issues when accessing non-common attributes (TypeScript)

In the process of developing a wrapper function, I am passing a refs property into a send function. The Event type used to construct my state machine is defined as an intersection between a base interface { refs: NodeRefs } and a union of possible event ob ...

Unveiling the magic behind using jasmine to spy on a generic

I am trying to spy on a generic method in TypeScript, but Jasmine is not recognizing it. Here is the code snippet: http: HttpClient <- Not actual code, just showing type. ... this.http.get<Customer[]>(url); In this code, I am trying to mock the ...

You are unable to assign to 'total' as it is a constant or a property that cannot be modified

Upon running ng build --prod in my project, I encountered the following error: src\app\components\xxxx\xxxx.component.html(116,100): : Cannot assign to 'total' because it is a constant or a read-only property. The proble ...

Error: Trying to access a property of an undefined variable (retrieving 'x')

As a newcomer to the MEAN stack, I am attempting to create some basic posts. However, I keep encountering an error that reads TypeError: Cannot read properties of undefined (reading 'title') when trying to issue a post. The strange thing is, when ...

The functionality of Angular Flex Layout's Static API for vertical or horizontal space-around with no alignment appears to be malfunctioning

Can someone explain why the spacing around alignment isn't functioning here? I'm getting the same result for space-between. What could I be overlooking? ...

Adding child arrays to a parent array in Angular 8 using push method

Upon filtering the data, the response obtained inside the findChildrens function is as follows: My expectation now is that if the object length of this.newRegion is greater than 1, then merge the children of the second object into the parent object's ...

Utilizing properties from the same object based on certain conditions

Here's a perplexing query that's been on my mind lately. I have this object with all the styles I need to apply to an element in my React app. const LinkStyle = { textDecoration : 'none', color : 'rgba(58, 62, 65, 1)', ...

Why isn't my Visual Studio updating and refreshing my browser after making changes to the Angular project?

Having added an Angular project and running it successfully with ng serve / npm start, I encountered an issue. After making changes to the project and saving them using ctrl+s or file/all save, the project server did not recompile and the browser did not ...

The Karma testing feature in Angular Quickstart encounters issues right from the start

When attempting to run karma tests after a clean install of the official Angular quickstart on Windows 10, I encountered an issue. Following a series of four commands, here is what happened: C:\projects\temp>git clone https://github.com/angul ...

Error: User authentication failed: username: `name` field is mandatory

While developing the backend of my app, I have integrated mongoose and Next.js. My current challenge is implementing a push function to add a new user to the database. As I am still relatively new to using mongoose, especially with typescript, I am followi ...

Update Observable by assigning it a new value of transformed information using the async pipe and RXJS

My service always returns data in the form of Observable<T>, and unfortunately, I am unable to modify this service. I have a button that triggers a method call to the service whenever it is clicked. This action results in a new Observable being retu ...

Angular 4 allows you to assign unique colors to each row index in an HTML table

My goal is to dynamically change the colors of selected rows every time a button outside the table is clicked. I am currently utilizing the latest version of Angular. While I am familiar with setting row colors using CSS, I am uncertain about how to manip ...