Home > Blockchain >  Spy on a field assignment using Jasmine
Spy on a field assignment using Jasmine

Time:01-19

How could I spy on a field assignment using Jasmine?

E.g. I have the object under test:

const testObj = {
    testObjField: null,
    testObjFunc: function() { this.testObjField = "foo"; }
}

Now I want to assert that the testObj.testObjFunc will assign the "foo" to the testObj.testObjField. How should I proceed?

Here is what I tried:

  //arrange
  const testObj = {
    testObjField: null,
    testObjFunc: function () {
      this.testObjField = 'foo';
    }
  };

  const testObjTestObjFieldSpy = spyOnProperty(testObj, 'testObjField', 'set');

  //act
  testObj.testObjFunc();

  //assert
  expect(testObjTestObjFieldSpy).toHaveBeenCalledWith('foo');

But I am getting the error:

Error: : Property testObjField does not have access type set

CodePudding user response:

You can't spy on fields, only on methods.

I would do this:

//arrange
  let testObj = {
    testObjField: null,
    testObjFunc: function () {
      this.testObjField = 'foo';
    }
  };

  // !! Get a copy of the original
  const originalTestObj = { ...testObj };

  //act
  testObj.testObjFunc();

  //assert
  expect(testObj.testObjField).toBe('foo');
  
  // !! Reset testObj to what it was if that is required
  testObj = { ...originalTestObj };
  • Related