stubble

2019-10-08 admin

stubble是什么

什么是stubble,Unit-testing helper to replace "require" in tested code

stubble使用教程帮助文档

Stubble!

Travis-CI Status Stubble is a tool for node.js to help aid in your unit testing. Stubble allows you to require your source files in such a way that you can stub out any requirements you choose to.

Installing

npm install stubble

Usage

Let’s say you have a simple server script, server.js:

var http = require('http');

server = http.createServer(function(req, res) {
  res.end('Hello World!');
});

server.listen(3000, '127.0.0.1');
module.exports = server;

Obviously, this could be tricky to have written in a TDD fashion, as simply requiring this script in your test would not work well. Stubble to the rescue! First, create a new Stubble instance with a hash of any modules you want Stubble to intercept. Assuming you are writing your tests in Jasmine, your spec might start by looking something like this:

var Stubble  = require('stubble'),
    req      = {},
    res      = {
      end: jasmine.createSpy('res.end')
    },
    server   = {
      listen: jasmine.createSpy('server.listen')
    },
    httpMock = {
      createServer: jasmine.createSpy('http.createServer').andReturn(server)
    },
    stub = new Stubble({http: httpMock});

Now that you have your Stubble instance, you can use this to require your module and make assertions against it.

var returned = stub.require(__dirname+'/server');
describe('server', function() {

  it('creates a server', function() {
    expect(http.createServer).toHaveBeenCalled();
  });

  it('calls res.end', function() {
    http.createServer.mostRecentCall.args[0](req, res);
    expect(res.end).toHaveBeenCalledWith('Hello World!');
  });

  it('starts the server', function() {
    expect(server.listen).toHaveBeenCalledWith(3000, '127.0.0.1');
  });

  it('exports the server', function() {
    expect(returned).toEqual(server);
  });
});

You can even make specific assertions about the require calls that were made.

expect(stub.required('http').toEqual(1);
expect(stub.required('path').toEqual(0);

Testing

To run tests against this module, simply install all dependencies and run the package test script:

npm install -d # Only needs to be run once
npm test

本站文章除注明转载外,均为本站原创或编译。欢迎任何形式的转载,但请务必注明出处。

转载请注明:文章转载自 JavaScript中文网 [https://www.javascriptcn.com]

本文地址:https://www.javascriptcn.com/read-76849.html

文章标题:stubble

回到顶部