【问题标题】:"Cannot find global value 'Promise'" Error in Mocha test摩卡测试中的“找不到全局值'Promise'”错误
【发布时间】:2023-03-10 15:35:01
【问题描述】:

以下与全栈 Node.js 问题有关。它涉及 Express、Mongoose 和 Mocha。

我有一个控制器模块,它带有一个处理 HTTP 调用的函数。它基本上将 Request 和 Response 对象作为其参数。在其中,它将表单数据从 Request 对象中提取出来,并将数据存储在多个 MongoDB 实例中。为了完成多个数据存储,我们使用对 Promise.all 的调用。这是在异步函数中完成的。类似于以下内容

async function saveData(data1 : Data1Interface, data2 : Data2Interface,
                         res: Response)
 {
     try
     {
        //Call 3 save methods each returning promised. Wait fLoginInfoModelor them all to be resolved.
        let [data1Handle, data2Handle]  = await Promise.all([saveData1(data1),
                                                      saveData2(data2)]);                                                      
        //if we get here all of the promises resolved.                
        //This data2Handle should be equal to the JSON {"id" : <UUID>}
        res.json(data2Handle);       
        res.status(200);
     }
     catch(err)
     {
         console.log("Error saving registration data” + err);
         res.json( {
            "message" : "Error saving registration data " + err
         });
         res.status(500);
     }
 }

在 saveData1 和 saveData2 中,我正在做类似的事情:

function saveData1(data : DataInterface) : Promise<any>
{
    let promise = new Promise(function(resolve : bluebird.resolve, reject : bluebird.reject)
        {
            Data1Model.create(data, function(err, 
                    data){
….
.
.
这很好用!我们在 Typescript 中完成所有这些工作。

但是我想用 Mocha 来测试这个方法。这就是问题开始的地方。为简洁起见,我在此示例中仅使用其中一种 Mongoose 模型。如果我尝试将以下代码作为 mocha 单元测试运行,则会收到以下错误消息。就 Promise 构造函数而言,我不确定它想要什么?

TSError: ⨯ 无法编译 TypeScript 找不到全局值“Promise”。 (2468) server/controllers/registration.server.controller.ts (128,17):ES5/ES3 中的异步函数或方法需要“Promise”构造函数。确保您有“Promise”构造函数的声明或在您的--lib 选项中包含“ES2015”。 (2705) server/controllers/registration.server.controller.ts (134,66): 'Promise' 仅指一种类型,但在这里用作值。 (2693)

请注意,第 128 行是“异步函数 saveData(data1 : Data1Interface, data2 : Data2Interface, res: Response) “

以下两行 “让 [data1Handle, data2Handle] = await Promise.all([saveData1(data1), 保存数据2(数据2)]); “ 和

“让 promise = new Promise(function(resolve : bluebird.resolve, reject : bluebird.reject)”

产生 “'Promise' 仅指一种类型,但在这里被用作值。” 错误。

Mocha 单元测试代码如下所示。

import 'mocha';
import { expect } from 'chai';
import * as sinon from 'sinon';
var config = require('../config/config');
import * as sinonmongoose from 'sinon-mongoose';
import * as controller from './registration.server.controller';
import { Request, Response } from 'express';
import { Data1Interface, Data1Model} from '../models/data1.server.model';
import * as mathUtilities from '../utilities/math.utilities';
import mongoose = require("mongoose"); 
import * as bluebird from 'mongoose';

(mongoose as any).Promise = bluebird.Promise;

//NOTE: This currently does not work. 
    

describe('Registration related tests', function () {

    beforeEach(()=>{

    });
    afterEach(()=>{
        //sinon.restore(authentication);
    });
    it('should return 200 OK valid outline', function (done) {
            let dummyRequest: any = {
                body: {
                    username: "awhelan",
                    password: "awhelan",
                    firstName : "Andrew",
                    lastName: "Whelan",
                    email: "awhelan@srcinc.com",
                    source: "none",
                    school: "Arizona",
                    consent: true,
                    dob: "1970-03-10",
                    gender:"Male",
                    interviewconsent: true,
                    recordingconsent: true
                }
            };
            let id = mathUtilities.createId("Andrew", "Whelan", "awhelan@srcinc.com");
            let retJson = "{id:" + id +"}";
            let dummyResponse: any = {
                json: function (data) {
                    expect(data).to.equal(retJson);
                    done();
                    return this;
                },
                sendStatus: function (code) {
                    expect(code).to.equal(200);
                    done();
                    return this;
                }
            };
            let req: Request = dummyRequest as Request;
            let res: Response = dummyResponse as Response;

          
            let mock = sinon.mock(Data1Model).expects('create').yields(null, { nModified: 1 });

            controller.register(req, res);

            sinon.restore(Data1Model.create);

        });
});

请注意,ts An async function or method in ES5/ES3 requires the 'Promise' constructor”中的建议没有帮助。

任何关于我如何克服这些错误的建议都将不胜感激。

-安德鲁

【问题讨论】:

    标签: javascript node.js mongodb asynchronous


    【解决方案1】:

    通过安装 es6-shim 类型来修复它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-20
      • 2013-07-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-13
      相关资源
      最近更新 更多