[英]Mocking out a typescript class import using enzyme
I try to test this Typescript class with Jest (snippet so you get the idea):我尝试用 Jest 测试这个 Typescript 类(片段让你明白):
import OrderService from '../../../services/api/OrderService';
class InstallationOverview {
// using OrderService somewhere
// ...
}
In my test I use enzyme在我的测试中我使用酶
shallow(<InstallationOverview />);
I get the following error:我收到以下错误:
TypeError: Cannot read property 'AUTH_SERVER_URL' of undefined
1 | class Envs {
2 |
> 3 | static AUTH_SERVER_URL = window["env"]["AUTH_SERVER_URL"];
| ^
4 | static AUTH_CLIENT_SECRET = window["env"]["AUTH_CLIENT_SECRET"];
5 | static SENSOR_TEST_SERVICE_WS = window["env"]["SENSOR_TEST_SERVICE_WS"];
6 | static SENSOR_TEST_SERVICE_URL = window["env"]["SENSOR_TEST_SERVICE_URL"];
at Object.<anonymous> (src/util/Envs.tsx:3:28)
at Object.<anonymous> (src/services/SensorTestWebsocketClient.tsx:3:1)
at Object.<anonymous> (src/redux/reducers/index.js:17:1)
at Object.<anonymous> (src/redux/store/index.js:2:1)
at Object.<anonymous> (src/util/NotificationManager.tsx:1:1)
at Object.<anonymous> (src/services/api/RestService.tsx:2:1)
at Object.<anonymous> (src/services/api/OrderService.tsx:1:1)
at Object.<anonymous> (src/content/order/installation/InstallationOverview.tsx:21:1)
at Object.<anonymous> (src/tests/InstallationOverview.test.jsx:2:1)´´´
As you can see env object in window is missing.如您所见,窗口中缺少 env 对象。 BUT for testing the InstallationOverview class I don't need all other services imported by the OrderService.但是为了测试 InstallationOverview 类,我不需要 OrderService 导入的所有其他服务。
I already tried mocking it with我已经试过嘲笑它
jest.mock('./src/services/api/OrderService');
but this doesn't have any impact, I think this applies AFTER shallowing, so after the exception.但这没有任何影响,我认为这适用于浅化之后,因此在异常之后。
then I tried to create a mock file for OrderService and put it under __mocks__
both relative to the test and to the target class.然后我尝试为 OrderService 创建一个模拟文件,并将它放在相对于测试和目标类的__mocks__
下。
then I tried setting jest config in package.json to然后我尝试将 package.json 中的 jest 配置设置为
"jest": {
"moduleNameMapper": {
"OrderService": "<rootDir>/tests/__mocks__/OrderService.tsx"
}
}
However, I mixed up jest and enzyme because I don't have any idea now to get it work.然而,我把玩笑和酶混为一谈,因为我现在不知道如何让它发挥作用。
Using jest.mock is the right approach.使用 jest.mock 是正确的方法。 Since the new version of react I declared my src folder as root folder so I had to adjust the path to mock services/api/OrderService
and I moved the mock call outside the it() function to the class route由于新版本的反应,我将我的 src 文件夹声明为根文件夹,因此我不得不调整模拟services/api/OrderService
的路径,并将 it() 函数之外的模拟调用移动到类路由
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.