0
class ThingWithRedis
  constructor: (@config) ->
    @redis = require('redis').createClient()

  push: (key, object) ->
    @redis.set(key, object)
  fetch: (key, amount) ->
    @redis.get key, (err, replies) ->
      console.log "|#{replies}|"

module.exports = ThingWithRedis

#if you uncomment these lines and run this file, redis works

#twr = new ThingWithRedis('some config value')
#twr.push('key1', 'hello2')
#twr.fetch('key1', 1)
#twr.redis.quit()

しかし、テストから:

ThingWithRedis = require '../thing_with_redis'

assert = require('assert')

describe 'ThingWithRedis', ->
  it 'should return the state pushed on', ->

    twr = new ThingWithRedis('config')
    twr.push('key1', 'hello1')
    twr.fetch('key1', 1)

    assert.equal(1, 1)

「hello1」が表示されることはありません。

しかし、コーヒーのthing_with_redis.coffeeをコメントなしで直接実行すると、「hello2」が表示されます。

それは私が実行したときです:

mocha --compilers coffee:coffee-script

redis が機能しなくなったようです。何か案は?

4

1 に答える 1

0

Redis 接続がまだ確立されていない可能性があります。テストを実行する前に、'ready' イベントを待ってみてください。

describe 'ThingWithRedis', ->
  it 'should return the state pushed on', ->

    twr = new ThingWithRedis('config')
    twr.redis.on 'ready', ->
      twr.push('key1', 'hello1')
      twr.fetch('key1', 1)

node_redis は、'ready' イベントの前に呼び出されたコマンドをキューに追加し、接続が確立されたときにそれらを処理することに注意することが重要です。redis が「準備完了」になる前に mocha が終了する可能性があります。

https://github.com/mranney/node_redis#ready

于 2012-10-24T23:05:51.367 に答える