Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

function call assertions #560

Closed
umairx97 opened this issue Aug 29, 2021 · 4 comments
Closed

function call assertions #560

umairx97 opened this issue Aug 29, 2021 · 4 comments

Comments

@umairx97
Copy link

umairx97 commented Aug 29, 2021

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
Copy link
Author

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: #555

@ljharb
Copy link
Collaborator

ljharb commented Aug 29, 2021

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
Copy link
Collaborator

Raynos commented Aug 29, 2021

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
Copy link
Author

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants