0

I don't know if I am stupid, but, I have installed web-request module:

npm install web-request

it is installed, it is present in node modules. I try to use it:

import * as WebRequest from 'web-request';
export class MyHttp {

public static getUrl() {

console.log('hello');
  WebRequest.get('http://www.google.com/').then(()=> {
     console.log('success'); 
});

}
 }

Then I use it in the test:

import {MyHttp} from '../../../services/MyHttp';

describe('Request', () => {

  fit('should be successful', () => {
   MyHttp.getUrl();
   setTimeout(()=> {
   expect(true).toBe(true);
},5000);

 });

 });

The console output is:

hello

I cannot see 'success' output at all.

The typings is ok, I am able to enter web-request\index.d.ts, that looks fine.

What am I doing wrong ? :(

4
  • 2
    Your test runner is exiting immediately because it's not aware that you are running async behavior. Read the jasmine docs for how to write an async test function. Commented Aug 22, 2016 at 18:17
  • Don't create classes consisting of only static methods, and don't export them: stackoverflow.com/q/29893591/1048572 Commented Aug 22, 2016 at 18:22
  • Have you tried adding a catch error handler to the promise? Commented Aug 22, 2016 at 18:23
  • Even when I use Promise then in the test it wont success either. I use static, so the tests are clear, I've read a rule, no new keyword in tests. Commented Aug 22, 2016 at 18:32

1 Answer 1

1

I'm assuming the tests needs a callback to be called in order for the test runner to know that it finished and that it is Async. Here is an example base on your code. You can read about jasmine for instance here.

import * as WebRequest from 'web-request';
export class MyHttp {
    public static async getUrl() {
        console.log('hello');
        await WebRequest.get('http://www.google.com/')
        console.log('success'); 
    }   
}
it('should be successful', () => {
    MyHttp.getUrl();
    expect(true).toBe(true);
});

edit: If you look in the docs of web-request it seems that they use await. There is no need for then after the function call. This pauses execution until the promise is resolved and gives you the value in the return object. While not suitable for all things it can make sense for testing.

Sign up to request clarification or add additional context in comments.

3 Comments

Yep, I tried that callback , it does not work either
I've changes my answer a bit.
function should be async

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.