我有一个使用create-react-app设置的React项目。在项目中,有一个char *string1= {'h', 'e', 'l', 'l', 'o', '\0' };
const char* string2;
sprintf(string2, "%s", string1);
printf(string2);
//outputs hello
类,它包含特定于环境的值。看起来像这样(用于说明的最小版本):
Configuration
由于此配置类在组件中广泛使用,因此有一个手动模拟程序来设置适当的测试值:
# src/Configuration.js
class Configuration {
getBackendUrl() { return "https://somewhere.com/" }
}
export default new Configuration();
该模拟程序在# src/__mocks__/Configuration.js
class Configuration {
getBackendUrl = jest.fn(() => {return "http://localhost:3001" });
}
export default new Configuration();
中全局加载:
setupTests.js
隐式使用# src/setupTests.js
jest.mock('./Configuration');
类的所有测试均能正确工作并使用模拟值。
但是现在我有一个测试,我想在其中声明Configuration
类的实际模拟值。以下测试代码被分解为核心要素,实际上,我是在使用Configuration
模拟API服务器,然后在redux中测试正确的处理方式。
nock
问题在于# src/somemodule/demo.test.js
import Configuration from '../Configuration';
describe('somemodule/demo', () => {
it('uses correct configuration values', () => {
expect(Configuration.getBackendUrl()).toEqual("http://localhost:3001")
});
});
始终是Configuration.getBackendUrl()
。我能以某种方式实现返回模拟值吗?
我可以通过在undefined
测试套件方法中手动覆盖模拟来解决此问题,但我希望避免重复:beforeEach
。
感谢您的帮助!
编辑:添加了模拟的实际使用代码。
答案 0 :(得分:0)
其他测试正确使用了模拟,但是测试套件中的import Configuration from '../Configuration';
行正在导入实际的Configuration
类,而不是模拟。
尝试将其更改为import Configuration from '../__mocks__/Configuration';
。
答案 1 :(得分:0)
在不反映实际使用的代码的情况下最初提出问题的道歉。
实际上Configuration
的模拟使用了以下代码(现在可以使用该代码来调整问题):
# src/__mocks__/Configuration.js
class Configuration {
getBackendUrl = jest.fn(() => {return "http://localhost:3001" });
}
export default new Configuration();
这将始终为每个方法返回MockInstance
,因此在测试中未定义。
如果将模拟程序固定为不使用jest.fn
调用,那么它将起作用:
# src/__mocks__/Configuration.js
class Configuration {
getBackendUrl(){ return "http://localhost:3001" };
}
export default new Configuration();
再次抱歉,也许对某人有帮助。