Variables are not being set when calling the Angular test method

Currently, I am in the process of learning Jasmine and I have encountered an issue that I need some help with. During my test case run, specifically on the line

expect(component.roleModal.visible).toBeTrue();
, I am receiving an error message stating Expected false to be true.

describe('ManageRolesComponent', () => {
  let component: ManageRolesComponent;
  let fixture: ComponentFixture<ManageRolesComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [FormsModule],
      providers: [HttpClient, HttpHandler],
      declarations: [ManageRolesComponent, RoleModalComponent],
      schemas: [NO_ERRORS_SCHEMA]
    }).compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(ManageRolesComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should open the add modal', () => {
    spyOn(component, 'onOpenAdd').and.callThrough();
    expect(component.roleModal.visible).toBeTrue();
    expect(component.roleModal.state).toBe(ModalRoleState.Add);
  });
});

The onOpenAdd() function is quite straightforward:

  public onOpenAdd() {
    this.roleModal.state = ModalRoleState.Add;
    this.roleModal.open();
  }

The same simplicity applies to the open() function:

  public open() {
    this.visible = true;
  }

I am puzzled as to why the test fails even though I am explicitly setting the value of visible to true. Is there something wrong with my approach or implementation? Any insights would be greatly appreciated.

Answer №1

for successful test execution:

remove change detection from the beforeEach hook

beforeEach(() => {
 fixture = TestBed.createComponent(ManageRolesComponent);
 component = fixture.componentInstance;
 // fixture.detectChanges(); remove this line
});

and add your change detection function right after setting up your spy

it('should open the add modal', () => {
 spyOn(component, 'onOpenAdd').and.callThrough();
 fixture.detectChanges();
 expect(component.roleModal.visible).toBeTrue();
 expect(component.roleModal.state).toBe(ModalRoleState.Add);
});

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

Displaying variables in JavaScript HTML

<script type ="text/javascript"> var current = 0; </script> <h3 style={{marginTop: '10', textAlign: 'center'}}><b>Current Status: <script type="text/javascript">document.write(cur ...

Embedding the current page URL in a hidden input field inside a form for submission

I am currently exploring ways to pass the URL of the current page through a hidden field in order to redirect back to that page after processing the form input. Initially, I attempted using javascript:location.href, but it seems to be passing it as a liter ...

Any suggestions for a more effective method of managing authentication in Angular2 rc3 besides using guards?

After upgrading to router 3.0.0-alpha.8, I encountered a hurdle with authentication in my existing Angular2 app. Previously, I handled login/authentication by extending the RouterOutlet with an AuthRouterOutletDirective. This allowed me to easily check if ...

What is the best way to determine which watchers are triggered in Vue.js?

Within my parent component, there are numerous nested child components. Whenever a click occurs on one of the child components, it triggers an update to the route. The parent component watches the route property and performs certain actions when it change ...

The file type stored in Firebase storage is identified as 'octet-stream' rather than the expected 'png/jpg' format

I am experiencing an issue with uploading images to Firebase storage. After uploading them, I notice that they are labeled as application/octet-stream instead of the expected types like image/jpeg or image/png. Below is the code snippet I am using: <in ...

Adding a Material UI Tooltip to the header name of a Material UI Datagrid - a step-by-step guide!

I've nearly completed my initial project, but the client is requesting that I include labels that appear when hovering over specific datagrid cells. Unfortunately, I haven't been able to find any solutions on Google for adding a Material UI Tool ...

What type of JavaScript scope is accessible by an anchor tag's href attribute?

My current query involves using an <a> tag to invoke a JavaScript function: <a href="javascript:doSomething();">link</a> In which scope does this JS function need to be defined in order to be reachable? Is declaring it globally necessar ...

Issues with JavaScript scripts functionality on my live server

Hey everyone, I'm new to this community and having some trouble with my index.html file. Everything works fine except for one script that only runs when I open the file directly with live server in VSCode. Can someone help me out? The script causing i ...

Trouble with using $.ajax to call a PHP function

Hey everyone, I hate to ask for help but I'm really stuck on this issue. I've tried everything and followed all the scenarios on this site, but I just can't seem to get it working. I even added alerts and echoes, but the function doesn' ...

Ensuring payload integrity using microrouter: A step-by-step guide

I have utilized this code to develop a microservice const { json, send } = require('micro') const { router, post } = require('microrouter') const stripe = require('stripe')(process.env.STRIPE_SECRET_KEY) console.log(process.e ...

Connecting a Database with NestJS and TypeORM: A step-by-step guide to establish a connection with TypeORM and ensure easy access to

Could someone please explain how to create a DB instance using TypeORM? I want it to be accessible like this service, but the Connection class is deprecated. import { Inject, Injectable } from '@nestjs/common'; import { Connection, Repository } ...

Display the element when the button is clicked, only if the button is located in component A and the element is located

I am trying to display a div when a button is clicked, but the button and the div are located in different components. How can I make them communicate with each other? As a beginner in Angular4, any suggestions on a better approach would be greatly apprec ...

Choose the list item below

I'm working on a website that includes a select list with images. Here's what I have so far: When I choose an image from the list, it should display below. <?php // Establish database connection $con=mysqli_connect("******","***","*** ...

When a user clicks on an element, use jQuery to show a specific

I am looking to extract the Admission ID field within a separate function that triggers when a user clicks on a button. $(document).ready(function () { $.each(data.student, function (i, item){ trHTML += '<tr>'+ ...

Using TypeScript to patiently wait for an observable or promise to complete before returning an observable

As a newcomer to TypeScript & RxJS, my goal is to return an Observable once another Observable has completed: public myObservable = () : Observable<boolean> => { console.log('Retrieving the token from the database'); return ...

Having difficulty updating the parent for all PortfolioItem/Feature that were copied for a specific PortfolioItem/MMF

I'm facing a challenge in setting the parent for multiple features that I've copied for a specific MMF. However, only the parent of the last feature is being set. Below is the code snippet responsible for setting the parent: Record represents th ...

Error message: "Error encountered while building Next.js - ReferenceError: 'describe' is not defined"

I am facing difficulties achieving a successful next build without encountering the following error: > Build error occurred { ReferenceError: describe is not defined Although the dev server and tests execute smoothly, it appears that the jest global d ...

"Encountering an issue with Angular's npm run serve:ssr

When executing npm run serve:ssr, the terminal is flooded with a stream of minified characters which ultimately leads to a failure with this error message: Error: ENOENT: no such file or directory, open 'google/protobuf/api.proto' at Object.open ...

ng-view or controller appears to be malfunctioning

I'm currently working on a small web application using AngularJS. I have an index.html file in the main directory and three other HTML pages within the html subdirectory. login.html list.html detail.html Initially, the index.html should load the ...

changing session variables in JavaScript

My index.php page contains all my PHP functions, JavaScript code, and HTML tags. I am trying to figure out how to call a PHP function (addToCart($itemID)) to update session variables when the user clicks on a button (add to cart). Can you provide guidanc ...