使用 Webpack、Jasmine (-core)、typescript 进行单元测试 [英] Unit testing with Webpack, Jasmine (-core), typescript

查看:19
本文介绍了使用 Webpack、Jasmine (-core)、typescript 进行单元测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个项目正在使用 webpack 将所有代码捆绑到一个文件中.该项目正在使用 Typescript,目前运行良好.

I have a project that is using webpack to bundle all code into a single file. The project is using Typescript and it is working fine at the moment.

我已经开始添加单元测试,而 jasmine 似乎是前进的方式(众多方式之一).它实际上包含在 package.json 中的 jasmine-core - 不确定这有多大的不同.

I've gone to add unit testing and jasmine seems to be the way (one of the many ways) forward. Its actually jasmine-core that is included in the package.json - not sure how much of a difference that makes.

所以运行一个非常简单的测试,比如

So running a very simple test such as

it('true is true', function(){ expect(true).toEqual(true); });

工作正常.但是当我添加需要使用导入的测试时 - 例如

works fine. But when I add tests that require the use of an import - eg

import MyService = require('./MyServices');

然后,当我运行测试时,它会抱怨,因为它不知道要求"是什么.Uncaught ReferenceError: require is not defined

then when I run the tests it complains as it doesn't know what 'require' is. Uncaught ReferenceError: require is not defined

现在我猜这是因为我需要以与打包主项目类似的方式打包测试模块.

Now I'm guessing this is because I need to package up the test module in a similar way that I package up the main project.

那么最好的方法是什么?我是否应该在 webpack.config.js 文件中有多个入口点 - 每个 *.spec.ts 文件一个?或者有没有办法说接受未知数量的规范文件

So what is the best way to do this? Should I have multiple entry points in the webpack.config.js file - one for each *.spec.ts file? Or is there a way to have say accept an unknown number of spec files

entry:[ *.spec.ts ] 并让它为每个输出一个 js 文件 - *.spec.js

entry:[ *.spec.ts ] and have it output a js file for each one - *.spec.js

推荐答案

你可以使用 karma/karma-webpack 使用 webpack 运行所有测试来解析导入.您可以查看此存储库进行简单配置.

You can use karma/karma-webpack to run all the tests using webpack for resolving the imports. You can take a look at this repository for a simple configuration.

如果您不想为每个 spec.ts你的 webpack 的配置文件.

You can also specify an index.spec.ts as en entry point and make this file require all the spec files if you don't want to make one entry point for each spec.ts in your webpack's configuration file.

这篇关于使用 Webpack、Jasmine (-core)、typescript 进行单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆