Reputation: 193
I've written a promise that makes a call and checks the response code. I want to test this using node. I keep getting "TypeError: index.GeneratePromise is not a function" and I can't figure out whats wrong.
I've tried wrapping the promise in another function, and calling that from the test file. This doesn't wait for the promise response, and the returned value is "undefined". I've tried multiple forms of promises, async/await etc. which also haven't worked.
My test
var assert = require('assert');
var index = require('../index');
describe('Basic Mocha String Test', function () {
it('promise', function () {
index.GeneratePromise().then(function(value) {
console.log("promise value: ", value);
assert.equal(value, 200);
});
});
});
My promise
exports.GeneratePromise = new Promise(function(resolve, reject) {
https.get('https://www.google.com/', (resp) => {
let data = '';
resp.on('data', (chunk) => {
data += chunk;
});
resp.on('end', () => {
console.log('status code: ', resp.statusCode)
resolve(resp.statusCode);
});
}).on("error", (err) => {
reject(err);
});
});
I'm hoping to have at least some value, not "undefined" returned. It's an issue of not waiting for my promise in the test file.
Upvotes: 1
Views: 995
Reputation: 26909
You are exporting an actual Promise, not a function that creates a Promise. Because of that, you shouldn't use the ()
. Additionally, it()
can provide you with a callback to tell mocha your test is done. See mochas async docs. Try this:
var assert = require('assert');
var index = require('../index');
describe('Basic Mocha String Test', function () {
it('promise', function (done) {
//index.GeneratePromise().then(function(value) {
index.GeneratePromise.then(function(value) { // Notice there is no ()
console.log("promise value: ", value);
assert.equal(value, 200);
done(); // This tells mocha your test is done
});
});
});
Upvotes: 1