【问题标题】:Jasmine: require is not defined茉莉花:未定义要求
【发布时间】:2017-09-28 01:19:21
【问题描述】:

我通过这个链接做了 angular2 快速启动项目:https://angular.io/guide/quickstart。唯一不同的是我在 app.component.ts 中添加了代码var fs = require('js'),它可以工作。但是当我为该组件编写 Jasmine 单元测试时,它显示require is not defined,有人知道如何解决这个问题吗?

注意:

我在整个项目中使用打字稿。

我尝试添加节点类型定义,但它并没有修复错误。

这是我的代码: 单元测试.html

<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="content-type" content="text/html;charset=utf-8">
    <title>Ng App Unit Tests</title>
    <link rel="stylesheet" href="node_modules/jasmine-core/lib/jasmine-core/jasmine.css">
    <script src="node_modules/jasmine-core/lib/jasmine-core/jasmine.js"></script>
    <script src="node_modules/jasmine-core/lib/jasmine-core/jasmine-html.js"></script>
    <script src="node_modules/jasmine-core/lib/jasmine-core/boot.js"></script>
    ...
</head>
<body>
<!-- Unit Testing Chapter #1: Proof of life.  -->
<script src="app/app.component.spec.js"></script>
</body>
</html>

【问题讨论】:

  • 请为您的规范运行器发布代码? - 我假设您使用的是 specrunner.html...
  • 和网站里的unit-tests.html一样,看我问题里的代码

标签: jasmine angular


【解决方案1】:

您需要包含 SystemJS 并导入您的规范。

类似:

<script src="~/node_modules/systemjs/dist/system.js" type="text/javascript"></script>
<script>  
    System.config({
        baseURL: '/app'
    });
      System.import('app.component.spec')
    .then(null, console.error.bind(console));
</script>

【讨论】:

  • 你能发布你的组件代码吗?我会为你创建一个 plunk
  • 这是我的笨蛋:plnkr.co/edit/zmmOQSZcRgpbIyifRKxx?p=preview 出于某种原因,它不起作用。但是在我的应用程序中,我有类似的代码,它可以工作,只是在测试时不起作用。
【解决方案2】:

您的代码缺少所有类成员的打字稿所需的 this 关键字。

将您的组件更改为:

import {Component} from 'angular2/core';

@Component({
    selector: 'my-app',
    template: '<h1>My First Angular 2 App</h1>'
})
export class AppComponent {

  constructor() {
      this.testReq();
  }

  testReq(str: string): string {
    /*  var fs = require('fs');
      var str = '123';
      return str;*/
  }
}

我认为您在这里误解了一些事情。 FS 是一个用于处理文件系统的节点库。当您在 Node 进程中时,这非常有效,但在您的示例中,您不是。您正在浏览器进程中运行,因此您无权访问任何节点库。

【讨论】:

  • 当然,我的代码比上面的要多,例如,我使用 fs 读取函数 testReq 中的文件(它们实际上在我的应用程序中有效,只是在 Jasmine 测试中无效)。在这个例子中,我只是简化了代码,让你知道我在哪里需要 fs。
猜你喜欢
  • 1970-01-01
  • 2012-08-15
  • 2018-06-26
  • 1970-01-01
  • 2015-04-24
  • 2015-05-17
  • 1970-01-01
  • 2013-10-17
  • 2014-11-13
相关资源
最近更新 更多