Jest:spyOn 测试失败,即使异步函数正在执行

问题描述

我正在尝试监视在子模块中调用的异步函数。这是我以前做过很多次的事情,所以我不知道为什么它会失败!这是(简化的)代码

routes.js:

const express = require('express');
const router = express.Router();
const { fetchSamples } = require('./controllers.js');

router.get('/fetch-samples',fetchSamples);

controllers.js

const { fetchSamplesFromDb } = require('./services');

exports.fetchSamples = (req,res) => {
  const data = await fetchSamplesFromDb(req.query.params);
  res.status(200).json(data);
};

services.js

exports.fetchSamplesFromDb = async params => {
  console.log('I get called!');
  const x = await xyz; // Other stuff....
};

失败的测试:

const request = require('supertest');
const app = require('../app.js'); // express web server
const services = require('../services.js');

it('responds with 200 when successful',async () => {
  const spy = jest.spyOn(services,'fetchSample');
  const response = await request(app).get('/fetch-samples');
  expect(response.status).toBe(200); // PASSES
  expect(spy).toHaveBeenCalled(); // FAILS
});

我不明白为什么不叫这个间谍。我想知道是不是因为它是异步的,但我一直无法通过测试。非常感谢您的指点!

解决方法

require 待测模块后,在模拟使用 jest.spyOn() 方法之前,还需要使用 services 模块并使用原始 fetchSamplesFromDB 方法进行解构。>

在测试用例函数中使用 jest.spyOn() 方法模拟 fetchSamplesFromDB 方法已经晚了。您可以像这样使用服务方法:

const services = require('./services');

exports.fetchSamples = async (req,res) => {
  const data = await services.fetchSamplesFromDb(req.query.params);
  res.status(200).json(data);
};

这样,jest.spyOn(services,'fetchSamplesFromDb') 就会起作用。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...