从库中模拟 ES6 class
Mocking an ES6 class from a library
我在库中有一个 WindowEnv
ES6 class,我正试图模拟它。 class 位于我的 React 应用所依赖的名为 @react-force/models
的包中。这是 WindowEnv
class:
的代码
// Env.ts in @react-force/models
export interface Env {
get: (varName: string) => string;
}
export class WindowEnv implements Env {
get(varName: string): string {
return (window as any)._env_[varName];
}
}
这是在我的应用程序中使用此 class 的代码:
const env = new WindowEnv();
export const api = axios.create({
baseURL: env.get('API_URL'),
});
我试图通过在 /__mocks__/@react-force/models.ts
中添加以下代码来模拟 WindowEnv
class:
// /__mocks__/@react-force/models.ts
export const WindowEnv = jest.fn(() => {
return {
get: (varName: string): string => {
switch (varName) {
case 'API_URL': {
return 'http://localhost:8080';
}
default: {
return '';
}
}
},
};
});
不幸的是,这没有任何区别。测试无法看到模拟并引发错误。我做错了什么?
模拟的 class 与整个项目一起可用 here。
正如 Jest 文档所述:
If the module you are mocking is a Node module (e.g.: lodash), the mock should be placed in the __mocks__
directory adjacent to node_modules (unless you configured roots to point to a folder other than the project root) and will be automatically mocked.
这样全局模块模拟就不会干扰驻留在 src
中的本地模块。
这是 Create React App 项目中 node_modules
模拟的 known issue。 __mocks__
需要移到 src
里面。
我在库中有一个 WindowEnv
ES6 class,我正试图模拟它。 class 位于我的 React 应用所依赖的名为 @react-force/models
的包中。这是 WindowEnv
class:
// Env.ts in @react-force/models
export interface Env {
get: (varName: string) => string;
}
export class WindowEnv implements Env {
get(varName: string): string {
return (window as any)._env_[varName];
}
}
这是在我的应用程序中使用此 class 的代码:
const env = new WindowEnv();
export const api = axios.create({
baseURL: env.get('API_URL'),
});
我试图通过在 /__mocks__/@react-force/models.ts
中添加以下代码来模拟 WindowEnv
class:
// /__mocks__/@react-force/models.ts
export const WindowEnv = jest.fn(() => {
return {
get: (varName: string): string => {
switch (varName) {
case 'API_URL': {
return 'http://localhost:8080';
}
default: {
return '';
}
}
},
};
});
不幸的是,这没有任何区别。测试无法看到模拟并引发错误。我做错了什么?
模拟的 class 与整个项目一起可用 here。
正如 Jest 文档所述:
If the module you are mocking is a Node module (e.g.: lodash), the mock should be placed in the
__mocks__
directory adjacent to node_modules (unless you configured roots to point to a folder other than the project root) and will be automatically mocked.
这样全局模块模拟就不会干扰驻留在 src
中的本地模块。
这是 Create React App 项目中 node_modules
模拟的 known issue。 __mocks__
需要移到 src
里面。