tape-testing / tape

tap-producing test harness for node and browsers
MIT License
5.77k stars 307 forks source link

function call assertions #560

Closed umairx97 closed 3 years ago

umairx97 commented 3 years ago

Hi, So i've been using tape for quite some time now, both in my personal projects and companies, but I'm finding there's no way to write an assertion that checks if a function has been called as part of another function. or maybe I haven't just looked hard enough

example of what i'm trying to do

// Test file
const test = require('tape')
const someFile = require('./somefile')

test('Should call function Y as well', t => {
  const response = someFile.func1()
  t.ok(response)
  t.toHaveBeenCalled(someFile.func2)
})
// someFile.js
function func1 () {
  return func2()
}

function func2 () {
  return 2
}

so is there any recommended way to do this, or maybe there's an internal function i'm missing on

Appreciate the help

umairx97 commented 3 years ago

Update: I just noticed this is a way to add assertions, if that's recommended how would I go about writing a toHaveBeenCalled assertion any examples would be great

original ticket this was commented on: https://github.com/substack/tape/issues/555

ljharb commented 3 years ago

In this case, you can't do it with tape as-is. You need an object mocking/spying library - which is what https://npmjs.com/sinon is for.

You can then make assertions about your sinon spies/mocks/stubs using tape.

Raynos commented 3 years ago

The alternative answer is that writing a test which checks what happens to the internals of a module is fragile and not a very useful test.

Your better of writing a test that checks the black box behavior of a module. Or changing the API of a module to make it easier to test.

If you want to write an assertion that a module for example does a logger.warn('oops', info) then passing in an instance of https://github.com/Raynos/testing-logger so that you can track and assert that the module does indeed emit useful log lines is a decent approach.

Changing the module would be something like someFile.func1(logger) or someFile.setLogger(logger)

umairx97 commented 3 years ago

Thank you both @Raynos and @ljharb, both suggestions are good, but I think for my case sinon is a better choice