【问题标题】:How to use jest.spyOn function to test a function from another file如何使用 jest.spyOn 函数测试另一个文件中的函数
【发布时间】:2019-06-17 07:50:39
【问题描述】:

我正在尝试运行测试用例来测试我的 Web 服务笑话的入口点 我在运行单元测试时面临一个问题。 无法监视异步函数,因为它是属性而不是函数。

我正在尝试测试是否在 server.js 文件中调用了 run 函数

入口文件有点像下面。


    import config from 'config';

    export default async function run() {
      try {
       /*
         some code
       */
      } catch (err) {
        process.exit(1);
      }
    }

    run();

测试文件如下所示


    import run from '../server';
    describe('server-test', () => {
    it('run', async () => {
        const start = require('../server');
        const spy = jest.spyOn(start, run);
        await run();
        expect(spy).toBeCalled();
      });
    });

测试应该可以正常运行, 但我在运行这个测试时遇到了错误

Cannot spy the async function run() {

    try {
            /*
             some code.
            */
          } catch (err) {
            process.exit(1);
          }
        } property because it is not a function; undefined given instead

【问题讨论】:

    标签: node.js jestjs spyon


    【解决方案1】:

    我为此错误研究了很长时间,并在以下帖子中结束 How to spy on a default exported function with Jest?

    因此,在不放弃默认关键字(即 ES 6 lint 所需)的情况下,唯一的解决方案是使用“默认”字词代替“运行”。

    有点像这样使用。

    const spy = jest.spyOn(start, 'default');

    它应该可以工作。

    【讨论】:

      猜你喜欢
      • 2019-06-26
      • 1970-01-01
      • 2019-03-10
      • 2020-08-20
      • 2014-05-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-13
      相关资源
      最近更新 更多