【发布时间】:2019-05-22 11:37:56
【问题描述】:
假设我有以下文件/代码:
Person.ts
export class Person {
id: string;
firstName: string;
lastName: string;
isEmployed: boolean = true;
isManager: boolean = false;
public static Name = ():string => this.firstName + ' ' + this.lastName;
}
WorkHistory.ts
import { Person } from './person';
export class WorkHistory {
public propA: string;
public propB: string;
public getHistory = (p: Person): any => {
// do something
// return history
};
}
格式化程序.ts
import { Person } from './person';
import { WorkHistory } from './workHistory';
export class Formatter {
public formatWork(p: Person) {
let wh: WorkHistory = new WorkHistory();
let whData = wh.getHistory(p);
// do formatting
// return formatting
}
}
我正在尝试为formatWork 方法编写单元测试。但是,我不知道如何存根 WorkHistory 及其属性。
这是我目前得到的:
Formatter.spec.ts
describe('formatWork', () => {
let mockWorkHistory = {
propA: '',
propB: ''
};
let sandbox;
let formatter;
beforeEach(() => {
sandbox = sinon.createSandbox();
sandbox.stub(WorkHistory, "prototype").value(mockWorkHistory);
});
afterEach(() => {
sandbox.restore();
});
it('should do something', () => {
// create person object
formatter = new Formatter();
var result = formatter.formatWork(person);
console.log(result);
});
});
我已经尝试过存根和sandbox.replace,但是,我似乎无法覆盖WorkHistory 默认属性或方法。
就目前而言,上述内容在 Phantom 2.1.1 中引发了异常:TypeError: Attempting to change enumerable attribute of unconfigurable property.
此外,我的夹具中的console.log 显示了WorkHistory 的所有默认属性,而不是覆盖的值。
我错过了什么?我做错了什么?
【问题讨论】:
标签: javascript typescript sinon