【发布时间】:2016-03-01 17:12:22
【问题描述】:
我一直在按照官方教程使用 Jasmine 在 Angular 2 中设置单元测试。我想模拟另一个类中定义的 Profile 对象。当我尝试使用其构造函数实例化 Profile 时,Web 控制台显示错误;它指出错误加载文件。
profile.ts
import {Injectable} from 'angular2/core';
export class Profile {
id: number;
name: string;
}
单元测试.html
<html>
<head>
<title>Jasmine 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>
<!-- #1. add the system.js and angular libraries -->
<script src="../node_modules/systemjs/dist/system.src.js"></script>
<script>
// #2. Configure systemjs to use the .js extension
// for imports from the app folder
System.config({
packages: {
'app': {defaultExtension: 'js'}
}
});
// #3. Import the spec file explicitly
Promise.all([
System.import('profile.spec.js')
])
// #4. wait for all imports to load ...
// then re-execute `window.onload` which
// triggers the Jasmine test-runner start
// or explain what went wrong
.then(window.onload)
.catch(console.error.bind(console));
</script>
</body>
</html>
profile.spec.ts
import {Profile, ProfileService} from '../app/profile';
var guy: Profile = new Profile();
describe("Initialising Profile", function() {
it("ID", function() {
expect(guy.id).toBe(1);
});
it("Name", function() {
expect(guy.name).toBe("Notguy");
});
});
Web 控制台错误:
GET XHR http://127.0.0.1:8080/app/profile
[HTTP/1.1 404 Not Found 1ms]
Error: XHR error (404 Not Found) loading http://127.0.0.1:8080/app/profile
Error loading http://127.0.0.1:8080/app/profile as "../app/profile" from http://127.0.0.1:8080/test/profile.spec.js
Stack trace:
error@http://127.0.0.1:8080/node_modules/systemjs/dist/system.src.js:1020:16
bootstrap/</fetchTextFromURL/xhr.onreadystatechange@http://127.0.0.1:8080/node_modules/systemjs/dist/system.src.js:1028:13
当我不调用构造函数时,控制台不会报错。
任何帮助将不胜感激。
编辑:简化的目录结构
root/
├── app
│ ├── boot.js
│ ├── boot.js.map
│ ├── boot.ts
│ ├── profile.js
│ ├── profile.js.map
│ ├── profile.ts
├── index.html
├── node_modules
├── npm-debug.log
├── package.json
├── test
│ ├── profile.spec.js
│ ├── profile.spec.js.map
│ ├── profile.spec.ts
│ └── unit-tests.html
└── tsconfig.json
【问题讨论】:
标签: unit-testing typescript jasmine angular