mockti icon indicating copy to clipboard operation
mockti copied to clipboard

Testing with real databases

Open artem-mindrov opened this issue 12 years ago • 3 comments

I have a database access object of sorts, and I needed to write unit tests for it. Stubbing Ti.Database APIs with empty functions was not an option, since I had to make sure the DAO actually makes changes to the database. Since I've already used mockti for other unit tests, I started looking for a way to make it play with SQLite on Node. This was not an easy task (especially with me being absolutely new to Node and Titanium), and I ended up forking this repo and porting it to a newer version of Node and node-gyp (since I had to build it on Windows). This is the code I'm using to mock Ti.Database:

class ResultSet
  constructor: (rows) -> 
    @rowIdx = 0
    @rows = []

    if rows.length
      @rowCount = rows.length
      @rows.push rows.item(i) for i in [0..rows.length-1]

  isValidRow: -> @rowIdx < @rowCount
  next: -> @rowIdx++
  fieldByName: (name) -> @rows[@rowIdx][name]
  field: (idx) -> require("lib/underscore").values(@rows[@rowIdx])[idx]
  close: -> 

class DB
  constructor: (@name) ->
    @lastInsertRowId = 0

  execute: (query, args...) ->
    sqlite = require "spec/lib/sqlite/sqlite"
    db = sqlite.openDatabaseSync @name
    console.log("running SQL #{query}")

    arg_array = []
    arg_array.push arg for arg in args
    result = db.query(query, arg_array)
    db.close()

    @resultSet = new ResultSet(result.rows)
    @lastInsertRowId = result.insertId if result.insertId
    @resultSet

  close: ->

Ti.Database = 
  open: (name) -> new DB(name)

Is there a chance something like this will be available? I could try to help if it makes any sense at all.

artem-mindrov avatar Sep 22 '12 10:09 artem-mindrov

I like this, and I'd be happy to accept a pull request to add this functionality. It is a Javascript project, however, so I'd expect new code to be in Javascript as well.

rf avatar Sep 22 '12 11:09 rf

I'll be happy to make a PR, but I'm not sure how to handle this external dependency. Should I publish a NPM package out of my fork and then list it in mockti's dependencies?

artem-mindrov avatar Sep 24 '12 11:09 artem-mindrov

Alright, I see, so you've fixed node-sqlite, this is the dependency you're talking about?

Ideally, you should make a PR on the original repo and have him publish it. However, if he's no longer a willing maintainer (which looks likely considering the 5 month old pull request), you should ask him if you can be added as an owner of the package in npm so you can publish using the same name.

rf avatar Sep 24 '12 15:09 rf