【问题标题】:Jest: spyOn test failing even though (async) function is executing开玩笑:即使(异步)函数正在执行,spyOn 测试也会失败
【发布时间】:2021-08-22 12:39:49
【问题描述】:

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

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
});

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

【问题讨论】:

    标签: javascript node.js express jestjs supertest


    【解决方案1】:

    在你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')就可以了。

    【讨论】:

    • 你明白了@slideshowp2!非常感谢!
    猜你喜欢
    • 2020-10-08
    • 2020-03-11
    • 2019-05-17
    • 2022-01-01
    • 2020-11-14
    • 2017-02-11
    • 1970-01-01
    • 1970-01-01
    • 2018-02-13
    相关资源
    最近更新 更多