WebBluetooth API の Mock が利用可能に



Google の Uri 氏が web-bluetooth-mock を公開してくれました。

テストには Facebook の Testing Framework である jest が利用されています。

このモックを利用したサンプルコード。
一例として、connectToDevice() メソッドを利用して、 0xffe0 を含むデバイスをスキャンして接続するかどうかをテストします。

import { WebBluetoothMock, DeviceMock } from './web-bluetooth.mock';
 
describe('connectToDevice', () => {
  it('should connect to bluetooth device', async () => {
    // Setup a Mock device and register the Web Bluetooth Mock
    const device = new DeviceMock('Dummy-Device', [0xffe0]);
    global.navigator = global.navigator || {};
    global.navigator.bluetooth = new WebBluetoothMock([device]);
 
    // This is a Jest specific mock, change to just `spyOn(...)` for Jasmine
    jest.spyOn(device.gatt, 'connect');
 
    // Calling the method we want to be tested
    await connectToDevice();
 
    // Checking if the function has been invoked. This also means
    // that requestDevice() has been called with a filter that matches
    // the device we defined above.
    expect(device.gatt.connect).toHaveBeenCalled();
  });


他のテストパターンのコードはこちらがとても参考になります。
https://github.com/urish/muse-js/blob/master/src/muse.spec.ts


iOS×BLE Core Bluetoothプログラミング

iOS×BLE Core Bluetoothプログラミング

改訂新版JavaScript本格入門 ?モダンスタイルによる基礎から現場での応用まで

改訂新版JavaScript本格入門 ?モダンスタイルによる基礎から現場での応用まで

Effective JavaScript JavaScriptを使うときに知っておきたい68の冴えたやり方

Effective JavaScript JavaScriptを使うときに知っておきたい68の冴えたやり方