简体   繁体   English

在打字稿中全部导入不起作用

[英]import all in typescript does not work

I don't know if I am stupid, but, I have installed web-request module: 我不知道自己是否愚蠢,但是,我已经安装了Web请求模块:

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. 可以输入,我可以输入web-request \\ index.d.ts,看起来不错。

What am I doing wrong ? 我究竟做错了什么 ? :( :(

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. 编辑:如果您在Web请求的文档中查找,似乎他们使用等待。 There is no need for then after the function call. 有没有必要then调用函数后。 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. 尽管不适合所有事物,但进行测试还是有意义的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM