Stub method of instance

I have an Express app that uses node-slack-sdk to make posts to Slack when certain endpoints are hit. I am trying to write integration tests for a route that, among many other things, calls a method from that library.

I would like to prevent all default behavior of certain methods from the Slack library, and simply assert that the methods were called with certain arguments.

I have attempted to simplify the problem. How can I stub a method (which is actually nested within chat ) of an instance of an WebClient , prevent the original functionality, and make assertions about what arguments it was called with?

I've tried a lot of things that haven't worked, so I'm editing this and providing a vastly simplified set-up here:

index.html :

const express = require('express');
const {WebClient} = require('@slack/client');
const app = express();
const web = new WebClient('token');

app.post('/', (req, res) => {

    web.chat.postMessage({
        text: 'Hello world!',
        token: '123'
    })
        .then(() => {
            res.json({});
        })
        .catch(err => {
            res.sendStatus(500);
        });
});

module.exports = app;

index.test.html

'use strict';
const app = require('../index');
const chai = require('chai');
const chaiHttp = require('chai-http');
const sinon = require('sinon');

const expect = chai.expect;
chai.use(chaiHttp);

const {WebClient} = require('@slack/client');


describe('POST /', function() {
    before(function() {
        // replace WebClient with a simplified implementation, or replace the whole module.
    });

    it('should call chat.update with specific arguments', function() {
        return chai.request(app).post('/').send({})
            .then(function(res) {
                expect(res).to.have.status(200);
                // assert that web.chat.postMessage was called with {message: 'Hello world!'}, etc
        });
    });
});

There are a few things that make this difficult and unlike other examples. One, we don't have access to the web instance in the tests, so we can't stub the methods directly. Two, the method is buried within the chat property, web.chat.postMessage , which is also unlike other examples I've seen in sinon, proxyquire, etc documentation.


The design of your example is not very testable which is why you're having these issues. In order to make it more testable and cohesive, it's better to pass in your WebClient object and other dependencies, rather than create them in your route.

const express = require('express');
const {WebClient} = require('@slack/client');
const app = express();//you should be passing this in as well. But for the sake of this example i'll leave it


module.exports = function(webClient) {
   app.post('/', (req, res) => {

       web.chat.postMessage({
          text: 'Hello world!',
          token: '123'
       })
           .then(() => {
              res.json({});
           })
           .catch(err => {
              res.sendStatus(500);
           });
   })
   return app;
};

In order to implement this, build your objects/routes at a higher module. (You might have to edit what express generated for you. I'm not sure, personally I work with a heavily refactored version of express to fit my needs.) By passing in your WebClient you can now create a stub for your test.

'use strict';

const chai = require('chai');
const chaiHttp = require('chai-http');
const sinon = require('sinon');

const expect = chai.expect;
chai.use(chaiHttp);
const {WebClient} = require('@slack/client');
const web = new WebClient('token');
let app = require('../index')(web);

describe('POST /', function() {

    it('should call chat.update with specific arguments', function() {
        const spy = sinon.spy();
        sinon.stub(web.chat, 'postMessage').callsFake(spy);

        return chai.request(app).post('/').send({})
            .then(function(res) {
                expect(res).to.have.status(200);
                assert(spy.calledWith({message: 'Hello world!'}));
        });
    });
});

This is known as Dependency Injection. Instead of having your index module build it's dependency, WebClient, your higher modules will pass in the dependency in order for the them to control the state of it's lower modules. Your higher module, your test, now has the control it needs to create a stub for the lower module, index.

The code above was just quick work. I haven't tested to see if it works, but it should answer your question.


So @Plee, has some good points in term of structuring. But my answer is more about the issue at hand, how to make the test work and things you need to understand. For getting better at writing unit tests you should use other good resources like books and articles, I assume there would be plenty of great resources online for the same

The first thing you do wrong in your tests is the first line itself

const app = require('../index');

Doing this, you load the index file which then executes the below code

const {WebClient} = require('@slack/client');
const app = express();
const web = new WebClient('token');

So now the module has loaded the original @slack/client and created an object which is not accessible outside the module. So we have lost our chance of customizing/spying/stubbing the module.

So the first thumb rule

Never load such modules globally in the test. Or otherwise never load them before stubbing

So next we want is that in our test, we should load the origin client library which we want to stub

'use strict';
const {WebClient} = require('@slack/client');
const sinon = require('sinon');

Now since we have no way of getting the created object in index.js , we need to capture the object when it gets created. This can be done like below

var current_client = null;

class MyWebClient extends WebClient {
    constructor(token, options) {
        super(token, options);
        current_client = this;
    }
}

require('@slack/client').WebClient = MyWebClient;

So now what we do is that original WebClient is replaced by our MyWebClient and when anyone creates an object of the same, we just capture that in current_client . This assumes that only one object will be created from the modules we load.

Next is to update our before method to stub the web.chat.postMessage method. So we update our before method like below

before(function() {
    current_client = null;
    app = require('../index');
    var stub = sinon.stub();
    stub.resolves({});
    current_client.chat.postMessage = stub;
});

And now comes the testing function, which we update like below

it('should call chat.update with specific arguments', function() {
    return chai.request(app).post('/').send({})
        .then(function(res) {
            expect(res).to.have.status(200);
            expect(current_client.chat.postMessage
                .getCall(0).args[0]).to.deep.equal({
                text: 'Hello world!',
                token: '123'
            });
        });
});

and the results are positive

结果

Below is the complete index.test.js I used, your index.js was unchanged

'use strict';
const {WebClient} = require('@slack/client');
const sinon = require('sinon');

var current_client = null;

class MyWebClient extends WebClient {
    constructor(token, options) {
        super(token, options);
        current_client = this;
    }
}

require('@slack/client').WebClient = MyWebClient;

const chai = require('chai');
const chaiHttp = require('chai-http');

const expect = chai.expect;
chai.use(chaiHttp);


let app = null;
describe('POST /', function() {
    before(function() {
        current_client = null;
        app = require('../index');
        var stub = sinon.stub();
        stub.resolves({});
        current_client.chat.postMessage = stub;
    });

    it('should call chat.update with specific arguments', function() {
        return chai.request(app).post('/').send({})
            .then(function(res) {
                expect(res).to.have.status(200);
                expect(current_client.chat.postMessage
                    .getCall(0).args[0]).to.deep.equal({
                    text: 'Hello world!',
                    token: '123'
                });
            });
    });
});

Based on the other comments, it seems like you are in a codebase where making a drastic refactor would be difficult. So here is how I would test without making any changes to your index.js .

I'm using the rewire library here to get and stub out the web variable from the index file.

'use strict';

const rewire = require('rewire');
const app = rewire('../index');

const chai = require('chai');
const chaiHttp = require('chai-http');
const sinon = require('sinon');

const expect = chai.expect;
chai.use(chaiHttp);

const web = app.__get__('web');

describe('POST /', function() {
    beforeEach(function() {
        this.sandbox = sinon.sandbox.create();
        this.sandbox.stub(web.chat);
    });

    afterEach(function() {
        this.sandbox.restore();
    });

    it('should call chat.update with specific arguments', function() {
        return chai.request(app).post('/').send({})
            .then(function(res) {
                expect(res).to.have.status(200);
                const called = web.chat.postMessage.calledWith({message: 'Hello world!'});
                expect(called).to.be.true;
        });
    });
});
链接地址: http://www.djcxy.com/p/82258.html

上一篇: 如何将接口与不同解决方案中的类关联起来

下一篇: 实例的存根方法