如何为单元测试模拟rxjs 6 webSocket函数?

时间:2019-03-29 10:33:24

标签: unit-testing websocket jasmine rxjs rxjs6

我正在尝试对使用rxjs6中的webSocket函数的某些代码进行单元测试。我尝试通过执行以下操作(建议here)来监视webSocket函数:-

import * as rxJsWebSocket from 'rxjs/webSocket';

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

但是我得到了错误:-

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

还有其他方法可以解决此问题吗?

我也尝试过ts-mock-imports,但没有成功。

1 个答案:

答案 0 :(得分:1)

使用"rxjs": "^6.6.3"对我有用。例如

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');
  });
});

单元测试结果:

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

源代码:https://github.com/mrdulin/jasmine-examples/tree/master/src/stackoverflow/55415481