【问题标题】:Jest Mocking promise not working with error Cannot read property 'then' of undefined in ExpressJSJest Mocking promise not working with error Cannot read property 'then' of undefined in ExpressJS
【发布时间】:2019-01-11 14:50:09
【问题描述】:

我正在尝试为我的 ExpressJS 应用程序实施测试。谷歌搜索后我找不到任何解决方案,请帮助并拯救我的一天......!

我遇到了错误。

TypeError: Cannot read property 'then' of undefined

       6 |   const arg1 = req.query.arg1;
       7 |   const arg2 = req.query.arg2;
    >  8 |   model.getExceptions(arg1, arg2, arg3)

测试文件如下

_test_/file.test.js:

import { getExceptions }  from '../file';
jest.mock('../model');

describe('file.js', () => {
  test('testing file...', () => {
    const req = {query: {arg1: 'SOME'}};
    const resp = {};
    expect(getExceptions(req, 'dd', resp)).toHaveLength(1);
    expect(getExceptions(req, 'ssd', resp)).toBe({test: 10});
  });
})

模拟文件:

_mocks_/model.js

const model = {
  getExceptions: (arg1, arg2, arg3) => {
  return new Promise((resolve, reject) => {
    process.nextTick(
      () =>
        arg1
          ? resolve({test: 110})
          : reject({
            error: 'not found.',
          })
    );
  })
}};

export default model;

要测试的代码文件:

文件.js

export const getExceptions = (req, res, next) => {
  const arg1 = req.query.arg1;
  const arg2 = req.query.arg2;
  model.getExceptions(arg1, arg2, req.arg3)
  .then(([rows]) => res.write(rows))
  .catch(next);
};

model.js

const model = {
  getExceptions: (arg1, arg2, arg3) => {
    try {
      return db.runQuery(qryName, [arg1, arg2, arg3]); // Custom function
    } catch (e) {
      throw new GatewayTimeoutError(e.message);
    }
  }
};

export default model;

如果需要更多详细信息,请告诉我。谢谢...

【问题讨论】:

    标签: node.js express promise mocking jestjs


    【解决方案1】:

    我终于找到了答案。 我会保留这个问题,以防有人遇到类似问题并寻找解决方案。

    这是一个非常简单的错误 - 模拟文件夹应该带有双破折号。

    正确的一个:

    __mocks__ 
    

    不正确的一个:

    _mocks_
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-02-12
      • 2021-09-20
      • 2021-06-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多