2

I am trying to unit test some code that uses the webSocket function from rxjs6. I have tried to spy on the webSocket function by doing the following (as recommended here): -

import * as rxJsWebSocket from 'rxjs/webSocket';

subject = new Subject();
webSocketSpy = spyOn(rxJsWebSocket, 'webSocket').and.returnValue(<any>subject);

but I got the error: -

Error: <spyOn> : webSocket is not declared writable or has no setter

Is there any other way to achieve this or is there a workaround for the error?

I've also tried ts-mock-imports with no success.

Ash McConnell
  • 1,340
  • 1
  • 17
  • 28

1 Answers1

2

It works for me using "rxjs": "^6.6.3". E.g.

index.ts:

import { webSocket } from 'rxjs/webSocket';

export function main() {
  return webSocket('ws://localhost:8081');
}

index.test.ts:

import { main } from './';
import * as rxJsWebSocket from 'rxjs/webSocket';
import { Subject } from 'rxjs/internal/Subject';

describe('55415481', () => {
  it('should pass', () => {
    const subject = new Subject();
    const webSocketSpy = spyOn(rxJsWebSocket, 'webSocket').and.returnValue(<any>subject);
    const actual = main();
    expect(actual).toBe(<any>subject);
    expect(webSocketSpy).toHaveBeenCalledWith('ws://localhost:8081');
  });
});

unit test result:

Executing 1 defined specs...
Running in random order... (seed: 21376)

Test Suites & Specs:
(node:74151) ExperimentalWarning: The fs.promises API is experimental

1. 55415481
   ✔ should pass (8ms)

>> Done!


Summary:

  Passed
Suites:  1 of 1
Specs:   1 of 1
Expects: 2 (0 failures)
Finished in 0.02 seconds

source code: https://github.com/mrdulin/jasmine-examples/tree/master/src/stackoverflow/55415481

Lin Du
  • 88,126
  • 95
  • 281
  • 483