首页 > 解决方案 > Jest Mocking promise not working with error Cannot read property 'then' of undefined in ExpressJS

问题描述

我正在尝试为我的 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);
};

模型.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.jsexpresspromisemockingjestjs

解决方案


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

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

正确一:

__mocks__ 

不正确的一个:

_mocks_

推荐阅读