oclif / fancy-test

extends mocha with helpful, chainable extensions

Home Page:https://npmjs.com/package/fancy-test

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

How to return different answers in any call using stub

joseglego opened this issue · comments

I'd like to test the behavior of my command, which is using a scraper. Basically, my CLI is connecting to a lib which is a scraper and get different information from a webpage which vary based on the parameter. So, in my tests I have to stub twice the same function, in each of them with a different return. I Thought it was cool. Because in the Fancy Test Documentation - stub section says:

Stub any object. Like all fancy plugins, it ensures that it is reset to normal after the test runs.

I tried in different ways, and none of them worked. Probably I'm missing something. So, I create 4 tests file with next tests:

But, sadly, In all these cases it fails, the answer from the stubed function was always the same. In other words, the return of the second or third call is like the first one even when I try to set a different stub (Is it the expected behavior? Am I doing something wrong). I know it's possible in Jest (with returns) and Mocha (with onCall().returns), and even with sinon, but, I couldn't recreate in fancy-test

(I had to delete these files, but mi repo is an Open Source project, which you can find and test in: https://github.com/joseglego/tibia-suite/tree/master/packages/cli)

It's weird, because in the Fancy Test Documentation - stub section I could find multiple definitions for stubs and it says:

Stub any object. Like all fancy plugins, it ensures that it is reset to normal after the test runs.

  • And the example do the same.
import * as os from 'os'

describe('stub tests', () => {
  fancy
  .stub(os, 'platform', () => 'foobar')
  .it('sets os', () => {
    expect(os.platform()).to.equal('foobar')
  })

  fancy
  .stub(os, 'platform', sinon.stub().returns('foobar'))
  .it('uses sinon', () => {
    expect(os.platform()).to.equal('foobar')
    expect(os.platform.called).to.equal(true)
  })
})

So, I'd like to know if there is something wrong in my code, or I have missing something. Am I not running the tests?

As I sayd before the problem was in my code.

test
    .stub(scraper, 'getCharacter', sinon.stub().returns(basicStub))
    .stdout()
    .command([
      'character',
      '--name="Basic Test"'
    ])
    .it('show character with basic information', ctx => {
      expect(ctx.stdout).to.equal(basicStoud)
    })

The command flag was in a wrong format. It should be

test
    .stub(scraper, 'getCharacter', sinon.stub().returns(basicStub))
    .stdout()
    .command([
      'character',
      '--name',
      'Test'
    ])
    .it('show character with basic information', ctx => {
      expect(ctx.stdout).to.equal(basicStoud)
    })