Jasmine : Techniques for monitoring a method callback using method.then()

Within my Angular 4.0.0 application, I have a method called in my component.

This method is invoked within a service:

this.myService.myMethod(param).then(any => {
    console.log("success case");
})
.catch(error => {
    console.log("error");
});

As I am working on unit testing, I am isolating my component by mocking the service. I mock this method as follows:

myMethodSpy = spyOn(service, 'myMethod').and.callFake((reg) => {
    return Observable.of('always error message');
});

However, when running the test, it seems that my spy method is not being called:

TypeError: this.service.myMethod(...).then is not a function

Do you have any insights on the root cause of this issue?

Answer №1

const fakePromise = {then: () => 'something'}
myMethodSpy= spyOn(service, 'myMethod').and.returnValue(fakePromise);

Alternatively, you have the option to return an actual promise.

const customPromise = new Promise((resolve, reject) => {
  resolve(someValue); 
  // or reject("failure reason"); 
});
myMethodSpy= spyOn(service, 'myMethod').and.returnValue(customPromise);

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

Invoke the subscribe function within the encompassing parent function

In crafting a versatile method, I have devised the following code snippet: fetchArticle(loading: Loading): void { this.articleService.getArticleById(this.data.definition.id) .map((response: any) => response.json()) .subscribe((response: ...

Angular 6: Addressing the 'ExpressionChangedAfterItHasBeenCheckedError' in dynamic form validation with reactive form by adding and removing elements

When utilizing Angular 6 Reactive Form and dynamically adding and removing new validators, an error occurs: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'disabled: false'. Current ...

What steps are needed to integrate the Prime MessageService into the Interceptor of an Angular application that exclusively utilizes Standalone Components?

I've been struggling to implement a global error notification feature, but I can't seem to inject anything into the Interceptor. The frustrating part is that there are no error messages - it simply doesn't work. If anyone has any insights on ...

Methods for assigning values to a formControl using an array

I have an array of objects and I am attempting to loop through the array, dynamically setting values to a formControl and not displaying anything if the value is null. I have searched for similar solutions but haven't found any references or examples ...

Is there a way to specialize generic methods in Typescript and make them more specific?

I am working with a generic static method in an abstract class: abstract class Base { static find<T extends Base>(options?: Object): Promise<T[]> { return findResults(options); } } Now, I am trying to specify its type in a derived cla ...

The interaction between Web API, Angular, and the unique MAC Address

My organization currently operates an Application using ASP MVC. However, the application is experiencing slow performance and confusion due to multiple programmers with conflicting ideas. I have taken on the task of refactoring and migrating it to Angular ...

What is the process for attaching a function to an object?

Here is the complete code: export interface IButton { click: Function; settings?: IButtonSettings; } abstract class Button implements IButton { click() {} } class ButtonReset extends Button { super() } The component looks like this: expor ...

Creating a variable name dynamically using Typescript

I am looking to efficiently create multiple instances of variables and assign values in a single statement, an example of which is shown below. this.myList1[data.id] = data.id + "-" + data.desc; this.myList2[data.id] = data.id + "-" + data.desc; this.myLi ...

Implement a class in Typescript that allows for the addition of properties at runtime

I'm currently in the process of incorporating Typescript definitions into an existing codebase that utilizes the Knockout library. Within the code, there is a prevalent pattern that appears as follows: interface SomeProperties { // Assorted prope ...

The issue of TypeError arising while invoking a method within TypeScript Class Inheritance

Currently, I am developing a Node.js application with TypeScript. In this project, I have a base controller class named BaseController and a derived controller called SettingController. The intention is for the SettingController to utilize methods from the ...

What is the best way to test an Angular application that uses class inheritance?

While I can successfully test normal controllers, I am facing issues when trying to test controllers that inherit a base controller. Our method of defining subclassed-controllers looks like this: app.NavController = app.BaseController.extend({ ... ...

The type 'TaskListProps[]' cannot be assigned to type 'TaskListProps'

I'm struggling with handling types in my TypeScript application, especially with the TaskListProps interface. export default interface TaskListProps { tasks: [ { list_id: string; title: string; description: string; status ...

CORS policy causing Socket.io communication issues in a Node.js and Angular app

I have a node.js server running with express and socket.io. When I try to communicate with a simple JavaScript client, everything works fine. However, when I attempt to establish communication with an Angular app (using ngx-socket-io), I encounter the foll ...

Angular auto-suggest components in material design

Can someone assist me in resolving my issue? I am trying to incorporate an autocomplete feature with a filter into my form. .ts file : contactArray; selectedContact: IContact; myControl = new FormControl(); filteredContact: Observable<string[] ...

Tips for sending information to a nested Angular 2 attribute component

As per the instructions found on this blog, in order to create inner components within an SVG using Angular 2, we need to utilize an [attribute] selector: // Within svgmap.component.ts file: component declaration @Component({ selector: '[svgmap]& ...

Tips for optimizing Angular source code to render HTML for better SEO performance

Our web platform utilizes Angular JS for the front-end and node js for the backend, creating dynamic pages. When inspecting the code by viewing the source, it appears like this: For our business to succeed, our website needs to be SEO-friendly in order to ...

Is SASS stylesheet supported by the Angular 2 Ahead-of-Time compiler?

Considering giving Angular 2 Ahead-of-Time compilation another shot. I'll have to do some significant refactoring since my current custom build process will need to be reworked. Prior to diving in, I'm curious: if I reference external .scss fil ...

How to transfer the label text value from html to .ts file in Ionic 3?

Hey everyone! I just started using Ionic and I'm wondering how to pass the value of a label text from HTML to the .ts file. Here's a snippet of my code: <div class="box" (click)="openChatBot()"></div> <ion-label>LEADER ...

Typescript encounters a failure in typing when an object is destructured

There is a function that returns an object with two properties (res, mes) where one of them could be null: const fetchJSON = <Res, Body>(link: string, body: Body): Promise<{ res: Res; mes: null } | { res: null; mes: Popup }> => { return n ...

Can someone explain how this "const s: string = ['a'][1];" is considered a valid Typescript expression?

I encountered an unexpected result when I executed the code const s: string = ['a'][1];. Instead of receiving a type error from the Typescript compiler, it returned undefined. This was surprising to me because I believed I was trying to assign an ...