node.js - 为什么 redis 命令不能在我的 CoffeeScript 文件的 mocha 测试中运行?

标签 node.js coffeescript redis mocha.js

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' 被打印出来。

但是当我直接运行 coffee thing_with_redis.coffee 并且底行未注释时,您确实看到打印了“hello2”。

这是我运行的时候:

mocha --compilers coffee:coffee-script

redis 似乎停止工作了。有什么想法吗?

最佳答案

有可能Redis连接还没有建立。在运行测试之前尝试等待“就绪”事件。

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'事件之前调用的命令添加到队列中,然后在建立连接时处理它们。有可能 mocha 在 redis ‘就绪’之前退出。

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

关于node.js - 为什么 redis 命令不能在我的 CoffeeScript 文件的 mocha 测试中运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12977935/

相关文章:

javascript - Coffeescript 循环谷歌位置自动完成

node.js - 如何使用 Node Restify 使路由过载

go - 为什么 lpop 会增加 Redis CPU 使用率?

php - *仅*在数据库表更改(添加行)时刷新 html 页面部分

javascript - 像普通用户一样使用你的机器人

javascript - 连接集合中所有元素的数组[MongoDB]

java - Jedis 永远阻止与亚马逊的连接

node.js - 使用 facebook nodejs sdk 发布到群组 : OAuthException

javascript - 调试 JS/CoffeeScript 代码 : Events, 回调等

session - 使用redis在不同的域/服务器上共享相同的php session