简体   繁体   中英

Testing: spyOn Helper class in angular

Is it possible to spyOn helper class? In the below code, StatefulPatternService.init() is calling a WebSocketHelper .

I would like to spyOn WebSocketHelper and mock the subscribeFn

  export class WebSocketHelper{ private url: string; constructor(url){ this.url = url; init(); } init(){ // init websocket & other login } } @Injectable({ providedIn: 'root' }) export class StatefulPatternService { constructor(){} private callback(_data){ } init(){ let wsHelper = new WebSocketHelper('/subscribe/topic'); // <-- How to spyOn??? wsHelper.subscribeFn = this.callback; // ... } } 

If spyOn won't be possible, then how it can be re-written so that this test can be covered?

Your challenge will be getting a hold of 'wsHelper' in order to spy on it. One thought: can you refactor to make wsHelper a class-scope variable instead? Then you could spyOn it when you get the service in the test suite, for example, something like:

service = TestBed.get(StatefulPatternService);
let spy = spyOn(service.wsHelper, 'subscribeFn');

Update

From the comments to my answer it looks like what you are really trying to do is verify that the constructor was called with the proper url. Since you are saving that in a class variable, there should be no need to spy on the constructor, but rather just test the value of the saved variable. As I mentioned in the comments, to do this you will need two things: to make wsHelper a class level variable, and to add a method on the WebSocketHelper class that returns the value of the private variable 'url' so you can test it. I've set up a stackblitz to demonstrate what I'm talking about here: STACKBLITZ Here is a snippet from that stackblitz:

describe('MyService', () => {
    let myService: StatefulPatternService;

    beforeEach(() => {
        TestBed.configureTestingModule({
            imports: [/* any imports needed */],
            providers: [ StatefulPatternService ]
        });
        myService = TestBed.get(StatefulPatternService);
    });

    it('should be createable', () => {
        expect(myService).toBeTruthy();
    });
    it('should construct wsHelper properly', () => {
        myService.init();
        expect(myService.wsHelper.get_url()).toEqual('/subscribe/topic');
    })
});

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