在测试之间关闭/清除模拟套接字

时间:2019-11-27 21:58:19

标签: websocket cypress

我正在使用mock-socket模拟websockets调用。

我有一个测试正在工作,但是它仅适用于一个测试,然后它说模拟服务器已经在侦听该URL:

describe('mock socket method 1', () => {
  let mockSocket;
  let mockServer;
  beforeEach(() => {
    cy.visit('/', {
      onBeforeLoad(win: Window): void {
        // @ts-ignore
        cy.stub(win, 'WebSocket', url => {
          mockServer = new Server(url).on('connection', socket => {
            console.log('mock socket connected');
            mockSocket = socket;
          });
          if (!mockServer) return new WebSocket(url);
        });
      },
    });
  });

  afterEach(() => {
    mockSocket.close()
  });

  it('gets a message', () => {
    const object = _createSettingsApiPutPayload(defaultSettingsState)
    mockSocket.send(JSON.stringify(object));
    cy.contains('Motion threshold')
  });
  it('gets a message', () => {
    const object = _createSettingsApiPutPayload(defaultSettingsState)
    mockSocket.send(JSON.stringify(object));
    cy.contains('Motion threshold')
  });
});

如果我将方法更改为before()而不是beforeEach可以使用,但是每次测试我都不会得到一个新鲜的环境。如您所见,我在mockSocket.close()中尝试了afterEach(),但这是行不通的。我已经尝试过cy.reload(),但这会导致CORS错误!

错误似乎被抛出

> 15 | ReactDOM.render(
  16 |   <AppWrapper/>,
  17 |   document.getElementById('root'),
  18 | );

AppWrapper是包裹在redux的AppContainer中的ProviderAppContainerApp连接到redux,这里是App

class App extends Component<AppProps> {

  settingsSubscription: W3CWebSocket;

  componentDidMount(): void {
    // subscribe to websockets
    this.settingsSubscription = this.subscribeToSettings(urls.SETTINGS_WS);

  }

  /**
   * Sets up the websockets subscription to the settings.
   * @param url the url of the websocket server
   * @return the subscription object
   */
  subscribeToSettings(url: string): W3CWebSocket {
    let settingsSubscription = new W3CWebSocket(url);
    settingsSubscription.onopen = () => console.log('WebSocket Client Connected (settings)');
    settingsSubscription.onclose = () => console.log('WebSocket Client Disconnected (settings)');
    settingsSubscription.onmessage = (message: MessageEvent) => this.handleSettingsMessage(message);
    return settingsSubscription;
  }
...
}

1 个答案:

答案 0 :(得分:0)

在文档中,他们使用 mockServer.stop() 来停止 mockServer 而不是关闭 mockSocket。这就是我正在做的事情,而且很可能也是您所需要的。

这是我所指的片段:

 // NOTE: this timeout is for creating another micro task that will happen after the above one
  setTimeout(() => {
    t.is(app.messages.length, 1);
    t.is(app.messages[0], 'test message from mock server', 'we have subbed our websocket backend');
    mockServer.stop(t.done);
  }, 100);

这里是存储库的链接: https://github.com/thoov/mock-socket/