我有一个正在测试的角度服务,它导入 const 来自另一个文件
const
import { environment } from "../environments/environment";
环境.ts就像
export const environment = { ...window.mainConfig, production: false };
window.mainConfig 是一个电子上下文桥暴露变量。它在中未定义 ng test 上下文,所以我不得不嘲笑它。
window.mainConfig
ng test
我尝试了以下
import * as environment from '../environments/environment'; describe("...",()=>{ beforeEach(() => { //... spyOnProperty(environment,"environment","get").and.returnValue({/* ... */}); //... }); });
但这给了 Error: <spyOnProperty> : environment is not declared configurable . 我该如何正确地嘲笑这一点?
Error: <spyOnProperty> : environment is not declared configurable
你能试试吗 Object.assign 以使用新属性覆盖内部属性。
Object.assign
Object.assign(environment, {/* ... */});
如果没有,您可以在属性之间运行循环,也可以手动分配值。
const mockEnv = {/* ... */}; for (const [key, value] of Object.entries(mockEnv)) { environment[key] = value; }
最理想的解决方案是在 angular.json ,环境替换,用于测试环境。这将在您开始测试时进行配置。
angular.json
"test": { ... "options": { ... "fileReplacements": [{ "replace": "src/environments/environment.ts", "with": "src/environments/environment.tst.ts" }], ...