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 ‘就绪’之前退出。
关于node.js - 为什么 redis 命令不能在我的 CoffeeScript 文件的 mocha 测试中运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12977935/