问题描述
我正在使用模拟程序运行测试,以便测试不会总是命中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';
...
两个问题:
- 关于如何添加条件模拟的任何想法?我认为模拟永远不会应用,因为
jest.mock
可能需要在任何导入之前被调用? - 通过网络进行测试的惯例是什么?如果仅使用模拟,则实际上只是在测试模拟,而不是网络请求代码.但是,如果我不使用模拟程序,那我就不必要点击API.
- Any idea for how to add conditional mocks? I think mocks never apply because
jest.mock
might need to be called before any imports? - 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
这篇关于有条件地运行带有或不带有模拟的测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!