简体   繁体   English

在不运行服务器的情况下测试Node.js服务器代码

[英]Test nodejs server code without running server

New to nodejs testing. 新的Node.js测试。

I have a nodejs server that runs some complex server side logic, and I'm looking at building a unit test runner for that code. 我有一个运行一些复杂服务器端逻辑的nodejs服务器,并且我正在寻找为该代码构建单元测试运行器。 I do not want to run the server and tests sending it requests though, as that doesn't expose all the modules and functions I want to test on the server side. 希望运行服务器和测试发送它虽然要求,为不公开所有我想测试服务器端模块和功能。 That will be more like integration testing. 那将更像集成测试。 I just want to import those server side files, which are written as AMD modules, and call their functions one by one in unit tests. 我只想导入那些作为AMD模块编写的服务器端文件,并在单元测试中一一调用它们的功能。

What's the best way to go about doing this? 这样做的最佳方法是什么?

You will want to start by installing a unit-test and assertion framework to your current project. 您将首先需要为当前项目安装单元测试和断言框架。 Then you will also want to add requirejs (r.js). 然后,您还需要添加requirejs (r.js)。

We are currently using mochajs for unit-testing with should as the assertion library. 我们目前正在使用mochajs进行单元测试,并将should作为断言库。 Both have great adoption and feature support for testing Node.js. 两者都具有测试Node.js的广泛采用和功能支持。

npm install mochajs shouldjs requirejs --save-dev

This will add three packages to your local node_modules as well as save them inside your package.json's devDependencies. 这会将三个包添加到本地node_modules并将它们保存在package.json的devDependencies中。

Go ahead and setup a unit test directory in your project and create a new test file, [your_module_name]_test.js: 继续,在项目中设置一个单元测试目录,并创建一个新的测试文件[your_module_name] _test.js:

const should = require('should'),
      foo = require('foo');

describe('foo', () => {
  it('returns the letter a', () => {
    foo().should.eql('a');
  });
});

In the test file you will want to require the module under test and then unit-test as usual. 在测试文件中,您将需要先进行测试,然后再进行单元测试。

You can then run the test through r.js 然后,您可以通过r.js运行测试

./node_modules/requirejs/bin/r.js [your_test_dir]/[your_module_name]_test.js

You can also install mochajs globally and then simply run the mocha command instead of using the bin inside of your local node_modules. 您还可以全局安装mochajs,然后仅运行mocha命令,而不使用本地node_modules内部的bin。

Best of luck, and hope this helps. 祝您好运,希望对您有所帮助。

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

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