【问题标题】:import all in typescript does not work在打字稿中导入全部不起作用
【发布时间】:2016-08-22 18:10:39
【问题描述】:

我不知道我是不是傻,但是,我已经安装了 web-request 模块:

npm install web-request

它已安装,它存在于节点模块中。 我尝试使用它:

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'); 
});

}
 }

然后我在测试中使用它:

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

describe('Request', () => {

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

 });

 });

控制台输出为:

hello

我根本看不到“成功”输出。

打字没问题,我可以输入web-request\index.d.ts,看起来不错。

我做错了什么? :(

【问题讨论】:

  • 您的测试运行程序将立即退出,因为它不知道您正在运行异步行为。阅读 jasmine 文档了解如何编写异步测试函数。
  • 不要创建只包含静态方法的类,也不要导出它们:stackoverflow.com/q/29893591/1048572
  • 您是否尝试过在 promise 中添加 catch 错误处理程序?
  • 即使我在测试中使用 Promise 也不会成功。我用的是静态的,所以测试很清楚,我看过一个规则,测试中没有新关键字。

标签: javascript node.js typescript npm


【解决方案1】:

我假设测试需要调用回调,以便测试运行程序知道它已完成并且它是异步的。这是基于您的代码的示例。您可以阅读有关茉莉花的信息,例如 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);
});

编辑:如果您查看web-request 的文档,似乎他们使用等待。函数调用后不需要then。这会暂停执行,直到 promise 得到解决并为您提供返回对象中的值。虽然并不适用于所有事物,但它对测试很有意义。

【讨论】:

  • 是的,我试过那个回调,它也不起作用
  • 我的答案有点改变了。
  • 函数应该是异步的
猜你喜欢
  • 2016-11-21
  • 2023-03-21
  • 2016-07-13
  • 2019-02-21
  • 2019-08-29
  • 2013-08-22
  • 1970-01-01
  • 2017-05-07
  • 1970-01-01
相关资源
最近更新 更多