Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/33.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Jest Node.js测试中从响应中检索JSON_Node.js_Typescript_Jestjs - Fatal编程技术网

在Jest Node.js测试中从响应中检索JSON

在Jest Node.js测试中从响应中检索JSON,node.js,typescript,jestjs,Node.js,Typescript,Jestjs,我正在用Jest测试Node/Express应用程序。我从这个Jest测试中得到了200个代码,但是JSON响应没有任何代码 import * as httpMocks from 'node-mocks-http'; import * as ctrlCars from '../src/controllers/cars'; describe('Test Cars', () => { it('should GET car by ID', () => {

我正在用Jest测试Node/Express应用程序。我从这个Jest测试中得到了200个代码,但是JSON响应没有任何代码

import * as httpMocks from 'node-mocks-http';
import * as ctrlCars from '../src/controllers/cars';

    describe('Test Cars', () => {
        it('should GET car by ID', () => {
            const request = httpMocks.createRequest({
                method: 'GET',
                url: '/cars',
                params: {
                    id: 2
                }
            });
            const response = httpMocks.createResponse();
            const next = function(err) { 
              console.log('resultNext: ', response._getData()); 
            };

            ctrlReels.getCar(request, response, next);

            // TODO
            console.log('result: ', response.statusCode);
            console.log('result: ', response.statusMessage);
            console.log('resultData: ', response._getData());
        });
    });

我在网上找到的示例使用。_getData()获取数据,然后将其解析为JSON,但在我的测试结果中,data不返回任何内容,resultNext根本不输出。

在谷歌搜索了很多次之后,我找到了答案,因此我将为下一个找到它的人回答我自己的问题()。在我的案例中实际上有两个问题

  • 在运行测试时,我没有在同一终端中导出我的dev环境变量。我的节点应用无法连接到数据库,因为我没有导出用户和密码。第二个问题掩盖了这一点

  • 我需要将EventEmitter添加到测试中,以捕获“发送”事件,然后显示该数据

    从“节点模拟http”导入*作为HttpMock

    从“../src/controllers/cars”导入*作为CtrlReel

    从“事件”导入{EventEmitter}

    描述('测试车',()=>{ 它('should GET car',done=>{ const request=httpMocks.createRequest({ 方法:“GET”, url:“/cars”, 参数:{ 身份证号码:2 } }); const response=httpMocks.createResponse({eventEmitter:eventEmitter}); const next=函数(err){ console.error('testerror:',err); })

    ctrlReels.getCar(request, response, next);
    response.on('end', () => {
        console.log('end');
        console.log(response._getData());
        done();
      });
    response.on('send', () => {
        console.log('send');
        console.log(response._getData());
        done();
    });
    
    })); });

  • 本例输出数据两次。一次用于发送事件,一次用于结束事件


    注意:我不知道代码格式是怎么回事。我试过。。。我真的这么做了。

    @DavidR你的意思是在测试环境之外?是的,我用的是邮递员,我知道这条路线是有效的