我想存根这样调用的方法:
let context = new AuthenticationContext(authAuthorityUrl, true)
context.acquireTokenWithUsernamePassword()
我这样定义了我的存根方法:
let stub = sandbox.stub(AuthenticationContext.prototype,'acquireTokenWithUsernamePassword').callsFake(fkFn)
但是当我运行代码时,我从真实的acquireTokenWithUsernamePassword抛出了一个错误,我不想调用
答案 0 :(得分:0)
应该可以。例如
AuthenticationContext.ts
:
export class AuthenticationContext {
constructor(private url: string, private flag: boolean) {}
public acquireTokenWithUsernamePassword() {
console.log('real implementation');
}
}
index.ts
:
import { AuthenticationContext } from './AuthenticationContext';
export function main() {
const authAuthorityUrl = 'localhost';
let context = new AuthenticationContext(authAuthorityUrl, true);
context.acquireTokenWithUsernamePassword();
}
index.test.ts
:
import { main } from './';
import sinon from 'sinon';
import { AuthenticationContext } from './AuthenticationContext';
describe('62797402', () => {
let sandbox;
before(() => {
sandbox = sinon.createSandbox();
});
it('should pass', () => {
const fkFn = () => console.log('fake implementation');
let stub = sandbox.stub(AuthenticationContext.prototype, 'acquireTokenWithUsernamePassword').callsFake(fkFn);
main();
sinon.assert.calledOnce(stub);
});
});
具有覆盖率报告的单元测试结果:
62797402
fake implementation
✓ should pass
1 passing (27ms)
--------------------------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
--------------------------|---------|----------|---------|---------|-------------------
All files | 88.89 | 100 | 66.67 | 87.5 |
AuthenticationContext.ts | 75 | 100 | 50 | 66.67 | 4
index.ts | 100 | 100 | 100 | 100 |
--------------------------|---------|----------|---------|---------|-------------------