Skip to content

expect(fn).withArgs(...) rebinds this in fn #146

@mrozbarry

Description

@mrozbarry

I am testing a module I have written that is expected in node as a plain old object, but some methods call other methods in the module.

For example, I have code similar to this in my module:

MyModule.js

module.exports = {
  thingA: function(a, b) {
    return this._thingB(a, b+1);
  },
  _thingB: function(a, b) {
    return /* some thing that uses both a and b */;
  }
}

My test looks like:

MyModule.spec.js

MyModule = require('../../modules/MyModule.js')
// ...
expect(MyModule.thingA).withArgs(1, 2).not.to.throwException();

Now, for my example, think of thingB as a private module method. I can avoid the issue by removing it from the exported object and just have the method local to the module. This makes it truly private and resolves my problem, but now I don't have a good way to test the private methods aside from implicit testing through public methods that call it.

Another option is pre-defining the module:

MyModule = {
  thingA: funciton(a, b) {
    MyModule._thingB(a, b+1);
  },
  _thingB: function(a, b) { /* ... */ }
}

module.exports = MyModule

I'm not opposed to this, since it's technically correct, but would it be possible to be able to do something like:

expect(MyModule.thingA).boundWithArgs(MyModule, ...args).not.to.throwException()

Using apply and call already accept a bounding variable, it just needs to be set.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions