我正在尝试对一些使用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,但没有成功。
发布于 2020-09-10 15:24:28
使用"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
https://stackoverflow.com/questions/55415481
复制相似问题