0

I am using jest for testing. I want to test the return of my function:

const xml2js = require('xml2js')

const parser = new xml2js.Parser()

function opmlParser(xmlData) {
  return new Promise((resolve, reject) => {
    parser.parseString(xmlData, (err, data) => {
      if (err !== null && data !== null) reject(err)
      resolve({})
    })
  })
}

The promise resolves {} in order to be in simple test case.

So, I want to test to following function, and I expect the result to be a promise containing {}.
I have the following code:

const fs = require('fs');

test('minimal-opml', () => {
  const xmlData = fs.readFileSync('test/opml-parser/opml/test1.opml')
  return expect(opmlParser(xmlData)).resolves.toEqual({})
})

As the Jest documentation say, I shoud use resolves statement before matching result and use return.

But, I got an issue:

TypeError: Cannot read property 'toEqual' of undefined

resolves return undefined, so I can't continue to test values.

I tried to add global.Promise = require.requireActual('promise'), but stills not work.

Do you have any idea what wrong I am doing?

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
Frilox
  • 815
  • 2
  • 13
  • 24
  • My answer was incorrect, sorry, I must have been thinking of a different testing framework. FWIW, when people are trying to help you, even if they're wrong, "Whatever this don't even answer my question." is hardly a polite response. – T.J. Crowder Apr 14 '17 at 18:05
  • Sorry, I didn't want to be rude, I just wanted to mark the point that your answer didn't match the question. But, yes the formulation was bad. Sorry, and thank you for trying to help me. – Frilox Apr 14 '17 at 18:34

2 Answers2

3

The resolves methode is avalaible from 20.0.0+. So it is not already avalable. source

This is why it return undefined.

Frilox
  • 815
  • 2
  • 13
  • 24
2

You have a few issues in checking for an error in the opmlParser function. You want to check if there is an error and reject, else resolve.

Try this (brackets for clarity, and you may need to refine this to your specific case):

if (err !== null) {
  reject(err)
} else {
  resolve({})
}
Mitch Lillie
  • 2,217
  • 18
  • 25
  • Thank you, I still have the issue. I edited my post with your fix. – Frilox Apr 14 '17 at 19:03
  • @Frilox: I've rolled back that edit. That's not how SO works. If you edit answers into the question, the answer becomes nonsense, looking like it just repeats what's in the question. – T.J. Crowder Apr 15 '17 at 06:55