Checking an Angular 2 Component with Constructor Argument

Imagine having an Angular 2 Component containing two input parameters:

@Component{... (omitted for clarity)}
export class SomeComponent {

@Input() a: number
@Input() b: number

}

When needing to test this component, the process typically involves something like:

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [
        SomeComponent,
      ],
    })
    .compileComponents();
  }));

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

The createComponent method doesn't allow passing any parameters or calling the constructor. How can one go about instantiating/testing the component with different number values?

Answer №1

JB Nizet highlighted the importance of initializing @input parameters in the beforeEach() function when working with components that have them:

beforeEach(() => {
    fixture = TestBed.createComponent(SomeComponent);
    component = fixture.componentInstance;
    component.a = 1;
    component.b = 2;
    fixture.detectChanges();
});

Make sure to follow this pattern for successful component initialization.

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

Leveraging Global Variables for Validation in Angular (Angular 10)

I am currently creating a form in Angular 10 which involves the use of validators. Specifically, I have been utilizing the Validators.min() method within my form... Instead of manually inputting the value '100' in the Validators.min('100&ap ...

Module '.tmp/Rx.min.js' could not be located

My system runs on Ubuntu os version 16.04 with Node v6.6.0 and Npm 3.10.3. I'm currently setting up a project with gulp, but encountering a common issue: Error Message: Cannot find module '.tmp/Rx.min.js' When running the command below to ...

Angular 4 get request using query strings

The initial code block is performing as anticipated fetchQuotes(): Observable<Quote[]> { return this.http.get(this.url) .map((res: Response) => res.json()) .catch((error: any) => Observable.throw(error.json().error || &apos ...

The "void" type cannot be assigned to the type "ObservableInput<{}>"

I recently encountered this issue after updating to TS 2.2.2, and I suspect that is the root cause... While the code still functions properly, I am now seeing this error. I attempted various solutions such as returning an empty observable, catching the re- ...

RTK update mutation: updating data efficiently without the need to refresh the page

I am facing an issue with my mui rating component in a post-rating scenario. Although the rating updates successfully in the data, the page does not refresh after a click event, and hence, the rating remains enabled. To address this, I have implemented a d ...

Implement dynamic routerLink binding with Angular 11

Having a value containing routerLink and queryParams, I am attempting to bind it in the HTML. anchorValue : string = `<a [routerLink]="['../category/new ']" [queryParams]="{ query: 'category' }" routerLinkActive = ...

React hook triggering re-render

A function has been implemented to retrieve and decode user claims from a token stored in local storage using a hook. export const useActiveUser = (): { user: IUserTokenClaims | null } => { const [user, setUser] = useState<IUserTokenClaims | nul ...

Retrieving the final element from a TypeScript JSON array

I am trying to retrieve the value of the "id" property from the last element in an array of JSON objects. While I can easily find each element by id, I specifically need to extract the value of the last "id" in the array of JSON objects. In the example p ...

When trying to call a function within a component in Angular2, it's important to remember that self.context

When I try to call a function upon instantiating an angular2 component, an error is triggered: TypeError: self.context.dummyFunc is not a function To illustrate the issue, consider the following example. Say we have this component: import { Componen ...

Guide on Implementing jQuery Plugin with Vue, Webpack, and Typescript

I am currently exploring the integration of the jQuery Plugin Chosen into my vue.js/Webpack project with TypeScript. After some research, I discovered that it is recommended to encapsulate the plugin within a custom Vue component. To kick things off, I m ...

Angular UI refresh triggered by database update

In my current setup, I have an angular application that interacts with a backend asp.net core web-API to retrieve data. The application allows multiple users to be logged in simultaneously. In the event that one user performs a specific action first, that ...

The compatibility issue between Bootstrap and Angular 2 is causing some challenges

Hey there, I recently enrolled in an Angular 2 course on udemy and everything was running smoothly until I encountered an issue while trying to install bootstrap. I followed the installation steps diligently, but whenever I attempt to add any bootstrap el ...

Countdown component in Ant Design failing to display correct date

I’m currently working on developing a specific date component using react in conjunction with antd. Below is the code snippet I am utilizing: import { Statistic, Col, Row } from 'antd'; const { Countdown } = Statistic; const deadline = Date.pa ...

Unable to display grid items in React material-ui grid list

export interface FlatsGridProps { flats: IClusterFlats[]; } export const FlatsGrid: React.StatelessComponent<FlatsGridProps> = (props: FlatsGridProps) => { if (props.flats.length === 0) { return (<div> empty </di ...

Having trouble with animation transition in Angular 6?

When it comes to animating the opening and closing of a Sidenav, what are some best practices? animations: [ trigger('slider', [ state('open', style( {} )), state('closed', style( ...

Understanding how to leverage styles.module.scss for implementing personalized styling within react-big-calendar

I'm currently working with the react-big-calendar library in order to develop a customized calendar. However, I've encountered an issue where the SCSS styling is not being applied correctly. export const JobnsCalendar = () => ( <Calendar ...

Access Select without needing to click on the child component

I am curious to learn how to open a Select from blueprint without relying on the click method of the child component used for rendering the select. <UserSelect items={allUsers} popoverProps={{ minimal: false }} noResults={<MenuItem disabled={ ...

Creating a dynamic path to an imported file in React: A step-by-step guide

Struggling with a dilemma regarding dynamically generated paths for importing files in React. I have utilized the map() function to generate a dynamic part of the code, consisting of a repetitive sequence of div elements, each housing an audio element. The ...

Function arity-based type guard

Consider a scenario where there is a function with multiple optional parameters. Why does the function's arity not have a type guard based on the arguments keyword and what are some solutions that do not require altering the implementation or resorti ...

Retrieve a type from a Union by matching a string property

Looking at the following structure: type Invitation = | { __typename?: 'ClientInvitation' email: string hash: string organizationName: string } | { __typename?: 'ExpertInvitation' email: strin ...