有条件地运行带有或不带有模拟的测试 [英] Conditionally run tests with or without mocks with jest

查看:55
本文介绍了有条件地运行带有或不带有模拟的测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用模拟程序运行测试,以便测试不会总是命中API.但是,我还想添加一个条件,以便可以使用相同的测试来测试API.

I'm running tests with mocks so that the tests don't always hit APIs. I however also want to add a condition, so that I can use the same test to tests the APIs.

但是,当我添加一个条件时,无论条件是true还是false,它都将忽略它并且永远不会应用模拟.

When I however add a condition, it ignores it and never applies the mocks no matter if the condition is true or false.

import config from 'config';
if(!config.test.useNetwork) {
    jest.mock('api/companies');
    jest.mock('api/articles');
}

import { searchCompany } from 'api/companies';
...

两个问题:

  1. 关于如何添加条件模拟的任何想法?我认为模拟永远不会应用,因为jest.mock可能需要在任何导入之前被调用?
  2. 通过网络进行测试的惯例是什么?如果仅使用模拟,则实际上只是在测试模拟,而不是网络请求代码.但是,如果我不使用模拟程序,那我就不必要点击API.
  1. Any idea for how to add conditional mocks? I think mocks never apply because jest.mock might need to be called before any imports?
  2. What's the convention for testing over the network? If I just use mocks, I'm really just testing the mocks, and not the network request code. But if I don't use mocks I'm unnecessarily hitting the API.

推荐答案

一个:

是,jest.mock()悬挂在代码块的顶部".但是,未提升jest.doMock.这样,您就可以完成您想要的事情:

Yes, jest.mock() is "hoisted to the top of the code block". However, jest.doMock is not hoisted. So, you can accomplish what you want thus:

const config = require('./config').default;
if(!config.test.useNetwork) {
    jest.doMock('api/companies');
    jest.doMock('api/articles');
}

const { searchCompany } = require('api/companies');

两个:

这是一个有争议的问题.它不适合StackOverflow,我也不会碰它

That's a controversial question. It isn't suited for StackOverflow and I'm not touching it lol

这篇关于有条件地运行带有或不带有模拟的测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆