Steps for confirming a property setting on an interface

I am working with the following interface

   export interface Command {
   id: CommandId;
   disabled: boolean;
}

My goal is to verify that the 'disabled' property has been changed. Here are my attempts:

1) Creating an object and checking if the property has been updated:

const command1: Command = {id: CommandId.Print, disabled: false};
// additional code here (refer below)
expect(command1.disabled).toBe(true);

Result:

TypeError: Cannot set property 'disabled' of undefined

2) Trying to create a Mock using typemock:

const command1 = Mock.ofType<Command>();
command1.setup(x => x.id).returns(() => CommandId.Print);
// additional code here (refer below)
command1.verify(x => x.disabled, Times.once());

Result:

TypeError: 'set' on proxy: trap returned falsish for property 'disabled'

3) Attempting to use spyOnProperty:

const command1 = {id: CommandId.Print, disabled: false} as Command;
spyOnProperty(command1, 'disabled');
// additional code following (refer below)

Result:

Error: Property disabled does not have access type get

I am struggling to find a solution to verify this. (I am still learning Angular and typescript)

The entire test method looks like this:

// arrange
const command1 = {id: TaskCommandId.Print, disabled: false} as Command;
spyOnProperty(command1, 'disabled');
const command2 = {id: CommandId.SaveTemplate, disabled: false } as Command;
spyOnProperty(command2, 'disabled');

const commands = [command1, command2];
mockService.setup(x => x.getCommands()).returns(() => commands);
const command1Update = {id: CommandId.Print, disabled: true } as CommandState;
component.ngOnInit();

// act
component.updateEnabledState(command1Update);

// assert
expect(command1.disabled).toHaveBeenCalled();
expect(command2.disabled).not.toHaveBeenCalled();

Answer №1

EnsureCalled() is designed to verify if a function has been called, like this:

spyOn(component, 'someOtherFn').and.callThrough();
component.ngOnInit();
expect(component.someOtherFn).EnsureCalled();

The example above should function correctly when the call to someOtherFn is within ngOnInit in your component, for instance:

ngOnInit() {
    someOtherFn();
}
someOtherFn() {
    console.log('2');
}

If you want to check whether a specific attribute of an object has been modified or not, you need to specifically target that attribute, such as:

component.object = {readOnly: true};
component.ngOnInit();
expect(component.object.readOnly).toBeTrue();

The outlined approach should function properly with the following code in your component:

object: any;
ngOnInit() {
  this.object.readOnly = false;
}

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

Error encountered: The combination of NextJS and Mongoose is causing a TypeError where it is unable to read properties of undefined, specifically when trying

Versions: Next.js 14.1 React 18 I am currently developing a profile section where users can update their profile information such as username, name, and profile photo. To achieve this, I have implemented a component that contains a form (using shadcn) to ...

Is it necessary to install ng-bootstrap if my project was built using the Bootstrap 4 alpha theme in Angular 4?

I am currently utilizing the SB-Admin-BS4-Angular-4-master theme in Angular 4. The theme includes a link to . My goal is to implement Bootstrap modals in my code. Following the documentation provided in the theme, I integrated the modals as per instruction ...

What is the best way to create and implement custom declaration files that are not available on @types or DefinitelyTyped?

I have encountered a situation where I am using an npm package named foo that is not available on DefinitelyTyped or may be outdated. Despite this, I still want to consume it under stricter settings like noImplicitAny, so I need to create custom definition ...

Identifying an SCSS file based on its class name in Angular

Currently, I'm utilizing an Angular 5 application with styles that are encapsulated within components. Upon running the ng serve command, all styles get inserted into <styles> tags within the <head> section of the page. This results in br ...

Add the component view to the webpage's body section

Using Angular 7 and ngx-bootstrap 4.0.1 Dependencies: "bootstrap": "3.3.7", "bootstrap-colorpicker": "2.5.1", "bootstrap-duallistbox": "3.0.6", "bootstrap-markdown": "2.10.0", "bootstrap-progressbar": "0.9.0", "bootstrap-slider": "9.8.0", "bootstrap-tags ...

What is the best way to retrieve a value from an array of objects containing both objects and strings in TypeScript?

Consider this scenario with an array: const testData = [ { properties: { number: 1, name: 'haha' } , second: 'this type'}, ['one', 'two', 'three'], ]; The goal is to access the value of 'second&ap ...

Problems with the duration of Shadcn Toasts (Inspired by the react-hot-toast library)

Within a 13.4 Nextjs project (app router), utilizing Typescript and TailwindCSS. I am currently exploring the usage of toasts provided by the remarkable shadcnUI Library, which draws inspiration from react-hot-toast while adding its own unique flair. Imp ...

I rely on the angular-responsive-carousel library for my project, but unfortunately, I am unable to customize the arrow and dots

When it comes to CSS, I utilize ng deep style in Angular 10 to make changes for browser CSS. However, I am facing an issue where the problem is not being resolved by my CSS code. Here is a snippet of my code: > ::ngdeep .carousel-arrow { > b ...

Exploring the process of linking a C# REST API to an Ionic 2 mobile application

I am completely lost on how to connect an asp.net web api with my ionic 2 mobile app. Any help or advice on resolving this problem would be greatly valued! ...

Adding an item into a list with TypeScript is as simple as inserting it in the correct

I am working with a list and want to insert something between items. I found a way to do it using the reduce method in JavaScript: const arr = [1, 2, 3]; arr.reduce((all, cur) => [ ...(all instanceof Array ? all : [all]), 0, cur ]) During the fir ...

Using Firebase with Angular 4 to fetch data from the database and show it in the browser

Currently diving into Angular 4 and utilizing Firebase database, but feeling a bit lost on how to showcase objects on my application's browser. I'm looking to extract user data and present it beautifully for the end-user. import { Component, OnI ...

Can you explain the significance of the @ symbol in TypeScript/Vue?

I've recently embarked on a new VueJS project and stumbled upon some unfamiliar syntax. I have highlighted the lines with comments below. file(example) : MyModule.vue const storeCompte = namespace("compte") // namespace is based on 'no ...

Is it possible to transfer files using web-bluetooth technology?

As I work on developing an embedded system that counts the number of cars, saves their speed and time data in a logs file using rsyslog. Simultaneously, I am creating a web-API (in Typescript/Angular with Electron for Desktop usage and later Web as well) t ...

Angular allows for the easy population of an array into an input box

I've been given a task to create 10 different input forms and populate them with an array of 10 users using Angular's looping functionality. By the end of this task, I expect to have 10 input forms filled with various user data from the array. ...

Typescript type for selecting only string[] keys in an object

I am looking for a specific type: interface Filter<P extends object> { label: string; options: FilterOption[]; key: StringArrayKeyOf<P>; } The definition of StringArrayKeyOf is as follows: type StringArrayKeyOf<T extends object> = ...

Error with Angular 2 observables in TypeScript

When a user types a search string into an input field, I want to implement a debounce feature that waits for at least 300 milliseconds before making a request to the _heroService using HTTP. Only modified search values should be sent to the service (distin ...

The fillFormValues function is not functioning properly within the mat-select element

I need help filling a form value by id. This function successfully retrieves the value: fillFormValues(expenseCategory: ExpenseCategory): void { console.log('response', expenseCategory.parent_category) this.aa= expenseCategory.parent_c ...

Receiving contextual information from Microsoft Teams within an Angular application integrated as a tab

I am currently integrating an Angular website into a Microsoft Teams tab. In order to perform certain computations, I need to retrieve the Team ID. To achieve this, I have recently added npm install --save @microsoft/teams-js. Below is the code snippet th ...

Ivy workspace encountered an error with Angular being undefined: <error>

Recently, I attempted to install Angular on my MacOS terminal by entering the command $ npm install -g @angular/cli Unfortunately, the installation kept failing and the terminal displayed an error message. Subsequently, I tried the command $ sudo npm inst ...

The nebular element is not displaying correctly

I recently followed the instructions in the official documentation to implement a nebular component into my project. Everything seemed to be working fine with the layout, but I ran into issues when trying to use the card component and other similar compone ...