简体   繁体   English

从JS测试文件中使用Karma和Jasmine测试编译的TypeScript

[英]Testing compiled TypeScript with Karma and Jasmine from a JS test file

I have a project with the following structure: 我有一个具有以下结构的项目:

build
- out.js
spec
- foo.spec.js
- bar.spec.js
src
- foo.ts
- bar.ts

The two .ts files are built down into out.js . 这两个.ts文件内置在out.js In my .spec.js files, I want to be able to reference out.js easily. 在我的.spec.js文件中,我希望能够轻松引用out.js

When using Karma/Jasmine in pure JS projects, I simply use RequireJS, and wrap my test files in a define(['a'], function(a) { ... }); 在纯JS项目中使用Karma / Jasmine时,我仅使用RequireJS,并将测试文件包装在define(['a'], function(a) { ... }); file. 文件。 Then, in a.js , the contents would be wrapped like this: 然后,在a.js ,内容将像这样包装:

define([], function() {
    Foo.prototype. .......
    Foo.prototype. .......

    return Foo; 
});

However, because out.js will be build by the TypeScript compiler, and therefore cannot be wrapped in the define(...) block, I am unable to correctly import it with RequireJS. 但是,由于out.js将由TypeScript编译器生成,因此无法包装在define(...)块中,因此我无法使用RequireJS正确导入它。


To clarify: 澄清:

With handwritten JS, such as below, I can import it into my test files fine: 使用如下所示的手写JS,我可以将其导入到我的测试文件中:

define([], function() {
    function Bla() { }
    Bla.prototype.hi = function () {
        return "hey";
    };
    return Bla;
});

With similar JS, but built with the TypeScript compiler and therefore missing the define([]) wrapper, I simply get undefined when I import it into my tests. 使用类似的JS,但使用TypeScript编译器构建,因此缺少define([])包装,将其导入测试时,我只是变得undefined

var Bla = (function () {
    function Bla() { }
    Bla.prototype.hi = function () {
        return "hey";
    };
    return Bla;
})();

How can I either configure the TypeScript compiler to wrap my compiled classes in the define() wrapper, or how can I configure my tests to import the class without it being wrapped in a define() wrapper? 如何配置TypeScript编译器以将已编译的类包装在define()包装器中,或者如何配置测试以导入类而不将其包装在define()包装器中?

You should to use "--module amd" parameter 您应该使用“ --module amd”参数

in visual studio 2015: Project/"your project" properties/Typescript Building/module system/amd 在Visual Studio 2015中:项目/“您的项目”属性/ Typescript建筑/模块系统/ amd

and next: 接下来:

bla.ts: bla.ts:

 function Bla() { } Bla.prototype.hi = function () { return "hey"; }; export = Bla; 

bla.js: bla.js:

 define(["require", "exports"], function (require, exports) { function Bla() { } Bla.prototype.hi = function () { return "hey"; }; return Bla; }); 

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

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