Automattic / Automattic/expect.js

expect(fn).withArgs(...) rebinds `this` in fn

Open
#146 0 comments 0 reactions 0 assignees View on GitHub
Dominant language
JavaScript
Stars
2.1k
Forks
207
PR merge metrics
No merged PRs in 30d

Description

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_

``` javascript
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_

``` javascript
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:

``` javascript
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:

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

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

Contributor guide

No contributing guide indexed for this repository

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.