chrisgriffith / ionic-native-mocks

Ionic Native Mocks are designed to be used as placeholders during development for the actual Ionic Native modules.
205 stars 42 forks source link

Use mocks for tests #7

Closed danielolivaresd closed 7 years ago

danielolivaresd commented 7 years ago

I am using unit and end to end tests on my app (with Karma, Jasmine and Protactor by following ionic-unit-testing-example).

Let's say I have a class that calls the actual Ionic Native wrapper for a plugin, but I want to test this component. For tests, I'd like to use the mock for that Ionic Native wrapper, instead of the wrapper itself. Please see the example below:

// My class using an Ionic Native wrapper
import { BLE } from '@ionic-native/ble';

export class ClassToBeTested {
  uuid: string
  ble: BLE

  constructor (uuid) {
    this.uuid = uuid
    this.ble = new BLE()
  }

  connect () {
    this.ble.connect(this.uuid)
    // ...
  }
}
// Test:
import { ClassToBeTested } from "../../lib/class_to_be_tested"

describe('ClassToBeTested', () => {
  it('can be instantiated', () => {
    let instance:ClassToBeTested = new ClassToBeTested("a")
    expect(instance instanceof ClassToBeTested).toBe(true)
    expect(instance.uuid).toBe("a")
  })

  it('can connect', () => {
    let instance:ClassToBeTested = new ClassToBeTested("a")
    expect(instance.connect).not.toThrow()
    // This fails: Expected function not to throw, but it threw TypeError: Cannot read property 'ble' of undefined.
  })
})

I think that what I need is to use BLEMock instead of BLE when testing. How can this be done?

danielolivaresd commented 7 years ago

Closing this since this blog post and writing my own mocks that use the Ionic Native mocks + Jasmine's spyOn() seem to do the trick for me.