简体   繁体   English

开玩笑:spyOn 测试失败,即使(异步)function 正在执行

[英]Jest: spyOn test failing even though (async) function is executing

I'm trying to spyOn an async function that's called within a submodule.我正在尝试监视在子模块中调用的异步 function。 This is something I've done many times before, so I can't work out why it's failing: Here's the (simplified) code:这是我以前做过很多次的事情,所以我无法弄清楚它失败的原因:这是(简化的)代码:

routes.js:路线.js:

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

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

controllers.js控制器.js

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

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

services.js服务.js

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

And the failing test:和失败的测试:

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

I can't work out why the spy isn't called.我不知道为什么不叫间谍。 I've wondered if it's because it's async, but I haven't been able to get the test to pass.我想知道是不是因为它是异步的,但我无法通过测试。 Would really appreciate some pointers!真的很感激一些指点!

After you require the module under test, before mocking use the jest.spyOn() method, the services module is also required and deconstructed with the original fetchSamplesFromDB method.require被测模块之后,在 mocking 使用jest.spyOn()方法之前,还需要services模块并使用原始fetchSamplesFromDB方法解构。

It's late when you use jest.spyOn() method to mock fetchSamplesFromDB method in test case function.当您在测试用例 function 中使用jest.spyOn()方法模拟fetchSamplesFromDB方法时,为时已晚。 You can use the service method like this:您可以像这样使用服务方法:

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

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

In this way, jest.spyOn(services, 'fetchSamplesFromDb') will work.这样, jest.spyOn(services, 'fetchSamplesFromDb')将起作用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM