Jasmine toEqual for complex objects (mixed with functions)

后端 未结 5 1837
鱼传尺愫
鱼传尺愫 2020-12-16 13:00

Currently, I have a function that sometimes return an object with some functions inside. When using expect(...).toEqual({...}) it doesn\'t seem to match those c

5条回答
  •  Happy的楠姐
    2020-12-16 13:37

    here's how I did it using the Jasmine 2 syntax.

    I created a customMatchers module in ../support/customMatchers.js (I like making modules).

    "use strict";
    
    /**
     *  Custom Jasmine matchers to make unit testing easier.
     */
    module.exports = {
      // compare two functions.
      toBeTheSameFunctionAs: function(util, customEqualityTesters) {
        let preProcess = function(func) {
          return JSON.stringify(func.toString()).replace(/(\\t|\\n)/g,'');
        };
    
        return {
          compare: function(actual, expected) {
            return {
              pass: (preProcess(actual) === preProcess(expected)),
              message: 'The functions were not the same'
            };
          }
        };
      }
    }
    

    Which is then used in my test as follows:

    "use strict";
    
    let someExternalFunction = require('../../lib/someExternalFunction');
    let thingBeingTested = require('../../lib/thingBeingTested');
    
    let customMatchers = require('../support/customMatchers');
    
    describe('myTests', function() {
    
      beforeEach(function() {
        jasmine.addMatchers(customMatchers);
    
        let app = {
          use: function() {}
        };
    
        spyOn(app, 'use');
        thingBeingTested(app);
      });
    
      it('calls app.use with the correct function', function() {
        expect(app.use.calls.count()).toBe(1);
        expect(app.use.calls.argsFor(0)).toBeTheSameFunctionAs(someExternalFunction);
      });
    
    });
    

提交回复
热议问题