I ran into a fun little error recently when working on a ReactJs application. In my application I was using SinonJs to setup some spies on a method, I wanted to capture the input arguments for verification. However, when I ran my test I received the following error.
Attempted to wrap undefined property handlOnAccountFilter as function
My method under test is setup as such
handleOnAccountFilter = (filterModel) => { // logic here }
I was using the above syntax is the proposed class property feature, which will automatically bind the this
context of the class to my method.
My sinon spy is setup as such
let handleOnAccountFilterSpy = null; beforeEach(() => { handleOnAccountFilterSpy = sinon.spy(AccountsListingPage.prototype, 'handleOnAccountFilter'); }); afterEach(() => { handleOnAccountFilterSpy.restore(); });
Everything looked right, but I was still getting this error. It turns out that this error is due in part in the way that the Class Property feature implements the handlOnAccountFilter. When you use this feature the method/property is added to the class as an instance method/property, not as a prototype method/property. This means that sinon is not able to gain access to it prior to creating an instance of the class.
To solve my issue I had to make a change in the implementation to the following
handleOnAccountFilter(filterModel) { // logic here }
After make the above change I needed to determine how I wanted to bind this
to my method (Cory show 5 ways to do this here). I chose to bind this
inside the constructor as below
constructor(props){ super(props); this.handleOnAccountFilter = this.handleOnAccountFilter.bind(this); }
I am not a huge fan of having to do this (pun intended), but oh well. This solved my issues.
Till next time