我(非常)是编写单元测试的新手,我想知道应该如何测试基于environment.ts
文件中设置的属性构造API端点的静态方法。 / p>
environment.ts
文件会随着环境的变化而变化,所以我很好奇在测试中如何适应该需求。
是否需要重构我的方法以使其更易于测试?例如,不是隐式引用environment.endpoint,而是将传递环境作为参数?我会模拟环境文件吗?
任何建议都会有所帮助。
import {environment} from '../../environments/environment';
export class Utilities {
public static constructAPIEndpoint(): string {
const hostname: string = environment.endpoint;
const protocol: string = environment.local ? 'http:' : 'https:';
return `${protocol}//${hostname}/`;
}
}
environments.ts
export const environment = {
production: false,
local: false,
hostname: 'localhost',
showLogs: true,
endpoint: 'foo-dev-graphapp.com',
appInsights: {
instrumentationKey: '123'
}
};
茉莉花测试:
import {environment} from '../../environments/environment';
it('constructAPIEndpoint() it should construct an endpoint based on environment.ts', () => {
const endpoint: string = Utilities.constructAPIEndpoint();
/// THIS DOESN'T SEEM - having to recreate logic inside constructAPIEndpoint()
const protocol: string = environment.local ? 'http:' : 'https';
expect(endpoint).toEqual(`${protocol}//${environment.endpoint}`);
});