简体   繁体   English

Sinonjs 不存根 class 方法

[英]Sinonjs not stubbing class method

I want to stub a method that I call like this:我想存根我这样调用的方法:

let context = new AuthenticationContext(authAuthorityUrl, true)
context.acquireTokenWithUsernamePassword() 

I defined my stub method like this:我这样定义我的存根方法:

let stub = sandbox.stub(AuthenticationContext.prototype,'acquireTokenWithUsernamePassword').callsFake(fkFn)

But when I run the code, I get an error thrown from the real acquireTokenWithUsernamePassword, which I don't want to call但是当我运行代码时,我从真正的 acquireTokenWithUsernamePassword 中得到一个错误,我不想调用它

It should work.它应该工作。 Eg例如

AuthenticationContext.ts : AuthenticationContext.ts

export class AuthenticationContext {
  constructor(private url: string, private flag: boolean) {}
  public acquireTokenWithUsernamePassword() {
    console.log('real implementation');
  }
}

index.ts : index.ts

import { AuthenticationContext } from './AuthenticationContext';

export function main() {
  const authAuthorityUrl = 'localhost';
  let context = new AuthenticationContext(authAuthorityUrl, true);
  context.acquireTokenWithUsernamePassword();
}

index.test.ts : 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);
  });
});

unit test result with coverage report:带有覆盖率报告的单元测试结果:

  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 |                   
--------------------------|---------|----------|---------|---------|-------------------

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM