亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

無法模擬 Promise 函數

無法模擬 Promise 函數

qq_笑_17 2023-10-20 16:12:06
我有以下 lambda (aws) 代碼:exports.APILambda = (databaseConnection) => {  return function (event, context, callback) {    context.callbackWaitsForEmptyEventLoop = false    const connection = databaseConnection()    connection.then((connection, query, args) => {      connection.query(queries(query, args), args)        .then(result => {          console.log(result)          connection.end()          callback(null, { data: result })        })        .catch(err => {          throw err        })    })      .catch(err => {        logger.error(`${err.stack}`)        callback(err)      })  }}databaseConnection是一個 mariaDb 連接,實現為:function databaseConnection () {  return mariadb.createConnection({    host: process.env.DB_HOST,    user: process.env.DB_USER,    password: process.env.DB_PASSWORD,    port: '3306',    database: 'test'  })}我的測試是:describe('on new query', () => {  it('returns data', async (done) => {    await runLambda(      ['person', ['John']],      (query) => {        expect(query).toHaveBeenCalledWith(          expect.arrayContaining(['person', ['John']])        )      }, done)  })})對于該測試,我必須編寫以下函數:async function runLambda (args, assertions, done) {  const query = jest.fn(args => {    return Promise.resolve({      'name': 'John',      'lastName': 'Wayne'    })  })  const onNewQuery = APILambda(async () => ({ query }))  const event = {}  const context = {}  await onNewQuery(    event,    context,    (err, result) => {      if (err) done(err)      assertions(query)      done(result)    }  )}但是當我運行它時我遇到了麻煩,它不斷拋出:TypeError: connection.end is not a function或者說args未定義。有人可以闡明如何正確地嘲笑這一點嗎?
查看完整描述

1 回答

?
慕仙森

TA貢獻1827條經驗 獲得超8個贊

您的代碼存在很多問題:

  1. 您應該為connection.end()方法創建模擬。

  2. 你不應該將成功的結果傳遞給done()回調

  3. 您應該返回一個數組來解析 的多個值connection.then()。

  4. 你沒有提供queries函數,所以我直接傳遞queryandargs參數。

  5. 你傳了args參數,但是你沒有使用它,我下面根據代碼的意思使用它

一個工作示例:

testUtils.js:

const { APILambda } = require('./apiLambda');

// 5. You passed `args` parameter, but you didn't use it, I use it below based on the meaning of code

async function runLambda(args, assertions, done) {

  const query = jest.fn(() => {

    return Promise.resolve({

      name: 'John',

      lastName: 'Wayne',

    });

  });

  // 1. create mock for `connection.end()` method.

  const end = jest.fn();


  // 3. You should return an array to resolve multiple values for connection.then()

  const onNewQuery = APILambda(async () => [{ query, end }, args, null]);


  const event = {};

  const context = {};

  await onNewQuery(event, context, (err, result) => {

    if (err) done(err);

    assertions(query);

    // 2. you should NOT pass successful result to done() callback

    done();

  });

}


module.exports = { runLambda };

apiLambda.js:


exports.APILambda = (databaseConnection) => {

  return function(event, context, callback) {

    context.callbackWaitsForEmptyEventLoop = false;


    const connection = databaseConnection();


    connection

      .then(([connection, query, args]) => {

        connection

          // 4. You didn't provide `queries` function, so I just pass `query` and `args` parameters directly.

          .query(query, args)

          .then((result) => {

            console.log(result);

            connection.end();

            callback(null, { data: result });

          })

          .catch((err) => {

            throw err;

          });

      })

      .catch((err) => {

        console.error(`${err.stack}`);

        callback(err);

      });

  };

};

apiLambda.test.js:


const { runLambda } = require('./testUtils');


describe('on new query', () => {

  it('returns data', async (done) => {

    await runLambda(

      ['person', ['John']],

      (query) => {

        expect(query).toHaveBeenCalledWith(['person', ['John']], null);

      },

      done,

    );

  });

});

單元測試結果:


 PASS  src/stackoverflow/65179710/apiLambda.test.js (9.195s)

  on new query

    ? returns data (16ms)


  console.log src/stackoverflow/65179710/apiLambda.js:341

    { name: 'John', lastName: 'Wayne' }


--------------|----------|----------|----------|----------|-------------------|

File          |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |

--------------|----------|----------|----------|----------|-------------------|

All files     |    85.19 |       50 |    81.82 |     87.5 |                   |

 apiLambda.js |       75 |      100 |    66.67 |       75 |          18,22,23 |

 testUtils.js |    93.33 |       50 |      100 |      100 |                19 |

--------------|----------|----------|----------|----------|-------------------|

Test Suites: 1 passed, 1 total

Tests:       1 passed, 1 total

Snapshots:   0 total

Time:        10.556s


查看完整回答
反對 回復 2023-10-20
  • 1 回答
  • 0 關注
  • 102 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號