简单节点http服务器单元测试 [英] Simple node http server unit test

查看:111
本文介绍了简单节点http服务器单元测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用TypeScript创建了一个NodeJs http服务器,并用Jest对所有内容进行了单元测试,除了基类,服务器本身:

I created a NodeJs http server in TypeScript and I've unit tested everything with Jest, except the base class, the server itself:

import { createServer} from 'http';
export class Server {

    public startServer() {
        createServer(async (req, res) => {
            if(req.url == 'case1') { 
               // do case1 stuff
            }
            if(req.url == 'case2') { 
               // do case2 stuff
            }
            res.end();
        }).listen(8080);
    }
}

我正在尝试这种方法:

import { Server } from '../../../src/app/Server/Server';
import * as http from 'http';
describe('Server test suite', () => {

    function fakeCreateServer() {
        return {}
    }

    test('start server', () => {
        const serverSpy = jest.spyOn(http, 'createServer').mockImplementation(fakeCreateServer);
        const server = new Server().startServer();
        expect(serverSpy).toBeCalled();
    });
});

有没有一种方法可以为'createServer'方法创建有效的虚假实现?也许模拟一些请求?非常感谢!

Is there a way a can create a valid fake implementation for the 'createServer' method? And maybe simulate some requests? Thanks a lot!

推荐答案

您要在此处测试什么逻辑?

What logic do you want to test here?

这种简单的服务器足以声明它,而无需进行单元测试.

Such a simple server is declarative enough to keep it without unit tests.

如果要测试是否调用了 createServer 只是通过 jest.mock('http');

If you want to test that createServer is invoked just mock http module by jest.mock('http');

这些表达式被开玩笑地抬起,以使其比常规导入具有更高的优先级. https://jestjs.io/docs/en/mock-functions#mocking-模块

Such expressions are lifted up by jest to give them precedence over regular imports. https://jestjs.io/docs/en/mock-functions#mocking-modules

import { Server } from '../../../src/app/Server/Server';
import * as http from 'http';

jest.mock('http', () => ({
  createServer: jest.fn(() => ({ listen: jest.fn() })),
}));

describe('Server', () => {

    it('should create server on port 8080', () => {
        const server = new Server().startServer();
        expect(http.createServer).toBeCalled();
    });
});

这篇关于简单节点http服务器单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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