我很难嘲笑redis createClient()
nodejs中使用mocha和sinon的方法。这是我的index.js的一个片段。在socket类中,有一个create redis连接。现在在我的单元测试中,我遇到了这个错误 TypeError: Cannot stub non-existent property createClient
. 我好像不明白为什么?是因为嘲弄的命令吗?
const express = require("express");
const http = require('http');
const redis = require('redis');
const expressApp = express();
const server = http.createServer(expressApp);
const io = require('socket.io')(server, {
pingInterval: 10000,
pingTimeout: 5000
});
const config = require('config');
const log = require('gelf-pro');
const HTTP_PORT = 3000;
// Socket IO call backs
io.on("connection", (client) => {
new Socket(client);
});
// export the server so it can be easily called for testing
exports.server = server.listen(HTTP_PORT, () => {
log.info('socketio server started at port ' + HTTP_PORT);
});
单元测试代码:
'use strict'
var expect = require('chai').expect
, redis = require('redis')
, redisMock = require('redis-mock')
, sinon = require('sinon')
, io = require('socket.io-client')
, ioOptions = {
transports: ['websocket']
, forceNew: true
, reconnection: false
}
, testMsg = JSON.stringify({message: 'HelloWorld'})
, sender
, receiver
describe('Chat Events', function(){
beforeEach(function(done){
sinon
.stub(redis.RedisClient.prototype, 'createClient')
.callsFake(function() {
console.log('mock redis called');
return redisMock.createClient();
});
// connect two io clients
sender = io('http://localhost:3000/', ioOptions)
receiver = io('http://localhost:3000/', ioOptions)
// finish beforeEach setup
done()
})
afterEach(function(done){
// disconnect io clients after each test
sender.disconnect()
receiver.disconnect()
done()
})
describe('Message Events', function(){
it('Clients should receive a message when the `message` event is emited.', function(done){
sender.emit('message', testMsg)
receiver.on('ackmessage', function(msg){
expect(msg).to.contains(testMsg)
done()
})
})
})
})
1条答案
按热度按时间pxy2qtax1#
redis.createClient
方法是一个独立的函数,而不是原型的方法。如果您使用typescript,我们可以检查redis
包裹。index.d.ts
:所以,你应该这样存根:
index.js
:const main = require('./');
const redis = require('redis');
const sinon = require('sinon');
describe('62909606', () => {
it('should pass', () => {
const createClientStub = sinon.stub(redis, 'createClient').callsFake(function() {
console.log('mock redis called');
});
main();
sinon.assert.calledOnce(createClientStub);
});
});
62909606
mock redis called
✓ should pass
1 passing (9ms)