NagRock / ts-mockito

Mocking library for TypeScript
MIT License
969 stars 93 forks source link

Check value of this in mock calls #186

Open awvalenti opened 4 years ago

awvalenti commented 4 years ago

I need to check that the this value of a function call is what I expect. I'll probably do it like this:

obj.mockedFunction = function() {
  myThis = this
}
obj.functionThatShouldCallMockedFunction()
expect(myThis).to.equal(obj)

How about ts-mockito having this feature? Something like:

// This is already possible
const [firstArg, secondArg] = capture(mockedFoo.sumTwoNumbers).last();

// This could be added
const { thisValue } = capture(mockedFoo.sumTwoNumbers).last();

// So I could check this
expect(thisValue)to.equal(obj)
NagRock commented 4 years ago

I'm not really sure what you want to achieve. this for mocked function will be mock instance or arrow function that were assigned to thenCall behavior etc. You will not get with this instance of real implementation object.

awvalenti commented 4 years ago

I would like to verify that my call was like:

expectedFunction.call(expectedThis, 1, 2)

and not like:

expectedFunction(1, 2) // no this
// or
expectedFunction.call(wrongThis, 1, 2)
NagRock commented 4 years ago

Sorry, still not sure what you want to achieve.

To check mocked function call you can use verify:

verify(obj.myFunc(expectedThis, 1, 2)).once();

I guess it will be easier to understand if you will share sample code with implementation that you want to check.

awvalenti commented 3 years ago

Hello, sorry for the delay. Hope the following example clarifies it. Consider this program:

const a = {}, b = {}

function f(x, y) {
  console.log(this === a && x === y)
}

f.call(a, 1, 1) // calls f with this = a. Will print true.
f.call(b, 1, 1) // calls f with this = b. Will print false.
f.call(a, 1, 2) // x and y are not equal here; will print false

this works pretty much like an ordinary parameter (like x and y).

I would like to write an automated test that verifies the this value passed to a function.

For ordinary parameters, I can do:

// Testing that the value of x and y are 1 and 2
expect(capture(mockedFoo.sumTwoNumbers).last()).to.deep.equal([1, 2])

I would like to do something like:

// Testing that the value of this is a
expect(capture(mockedFoo.sumTwoNumbers).last().this).to.equal(a)