简体   繁体   中英

Jasmine & Angular: Mocking nested methods of Class under Test

Honored community...

I am facing the following problem, which feels simple, but I can't find a solution...

I am testing a Controller-Class in Angular. It is legacy code with tons of dependency and I just want to write a unit test without mocking all the dependencies .

I am looking for a solution to mock nested functions , ie I call a method, and expect that the nested method was successfully called, without actually calling it.

A sample...

my-controller.ts

export class MyController {

   constructor () {}
   public init() {
      /* doStuff */
      this.initializeMyObject();
   }

   private initializeMyObject(): void {
     /*  doOtherStuff  */
   }
}

my-controller.spec.ts

describe('MyController', () => {
  let controller: MyController;

  configureTestSuite(() => {
    TestBed.configureTestingModule({
      schemas: [NO_ERRORS_SCHEMA],
      imports: [/*.. module imports ..*/],
      providers: [ MyController ],
    });
  });

  beforeEach(() => {
    controller = TestBed.get(MyController);
  });

  it('completion should be called', () => {
    // arrange
    spyOn(controller, 'initializeMyObject');

    // act
    controller.init();

    // assert
    expect(controller.initializeMyObject).toHaveBeenCalled();
  });

});

I know that we usually do not mock methods of the Class being tested, but I know from other programming languages like Java that it works, and I am just curious how to do it (in addition to the fact, that mocking all nested dependcies would be a total overhead...).

I've read something about jasmine.createSpyObj but I doubt that the solution will be something like jasmine.createSpyObj('this', ['initializeMyObject']) , please correct me if I am wrong.

(This is not part of the answer I am looking for, but if there exist some third party libs, I will be glad to have a recommendation and follow up.)

Help will be appreciated. Cheers.

There are different ways to mock individual class methods with Jasmine. Here are a few examples.

When a method has no return value ( void return type).

spyOn(object, 'method-name').and.callFake(() => null); 

When the method should return a given value.

spyOn(object, 'method-name').and.returnValue(value); 

When the method accepts parameter and should return a computed value based on them.

spyOn(object, 'method-name').and.callFake((p1, p2) => {
    // compute value
    return value;
}); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM