我一直在关注使用Jasmine在Angular 2中设置单元测试的官方教程。我想模拟另一个类中定义的Profile对象。当我尝试使用其构造函数实例化Profile时,Web控制台显示错误;它表示错误加载文件。
profile.ts
import {Injectable} from 'angular2/core';
export class Profile {
id: number;
name: string;
}
单位-的test.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
答案 0 :(得分:0)
我会按如下所述更改SystemJS配置:
<script>
System.config({
packages: {
'app': {
defaultExtension: 'js',
format: 'register'
},
'test': {
defaultExtension: 'js',
format: 'register'
}
}
});
Promise.all([
System.import('test/profile.spec')
])
.then(window.onload)
.catch(console.error.bind(console));
</script>