摩卡在测试后没有退出

时间:2018-05-16 13:56:10

标签: node.js mocha chai

我从Node开始测试。使用mocha,chai和nock(拦截外部HTTP api调用)。

我已经编写了3个测试,所有这些测试都是通过,但是,当我添加第3个测试时,mocha在运行测试后停止退出,没有错误或任何错误的指示。

如果我对第3次测试发表评论,则mocha退出就好了。

这是引起问题的测试':

describe('tokenizer.processFile(req, \'tokenize\')', () => {

    it('should tokenize a file', async () => {

        req = {
            file: {
                originalname: 'randomcards.txt',
                buffer: cardsFile_buffer
            },
            user: {
                displayName: user
            }
        };

        expect(Buffer.from(await tokenizer.processFile(req, 'tokenize'))).to.deep.equal(tokensFile_buffer);

    });

});

同样,那个测试是一个通行证,让我感到困惑。

这里是tokenizer.processFile的代码:

processFile: function(req, whatTo){

        combinedLogger.info(`Request to ${whatTo} ${req.file.originalname} received. Made by: ${req.user.displayName}`);

        return new Promise(function(resolve, reject){

            const lines = [], responses = [];

            const lineReader = require('readline').createInterface({
                input: require('streamifier').createReadStream(req.file.buffer)
            });

            lineReader.on('line', line => {
                lines.push(line);
            });

            lineReader.on('close', async () => {

                //process every line sequentially

                try {

                    //ensure DB connected to mass insert
                    await db_instance.get_pool();

                    for(const line of lines) {
                        var response;
                        req.current_value = line;
                        if (whatTo == 'tokenize'){

                            response = await Tokenize(line);
                            db_instance.insertAction(req, 'tokenize', response);
                        }
                        else if (whatTo == 'detokenize'){
                            combinedLogger.info(`Request to detokenize ${line} received. Made by: ${req.user.displayName}`);
                            response = await Detokenize(line);
                            db_instance.insertAction(req, 'detokenize', line);
                        }
                        responses.push(response);
                    }

                    resolve(responses.join("\r\n"));

                }
                catch(error){
                    reject(error);
                }
            });

        });

    }

函数Tokenize(value)和Detokenize(value)也在其他2个测试中调用,运行时,mocha退出就好了。

知道造成这种情况的原因是什么?

摩卡版:5.1.1

1 个答案:

答案 0 :(得分:9)

我知道现在回答这个问题有点晚了,但是我也遇到了类似的问题,并且看到了您的帖子。

在mocha 4.0.0中,他们更改了完成测试的行为。自here

  

如果在您的测试似乎“完成”之后,mocha进程仍然存在,则表明您的测试已安排了一些事情(异步),并且没有对自己进行适当的清理。你没有打开插座吗?

就您而言,似乎从未关闭对createReadStream()的呼叫。

因此,您有2个选择:

选项A:关闭fs并打开其他流(推荐)

选项B:使用--exit选项运行摩卡。