簡體   English   中英

在 ecmascript 中模擬靜態方法

[英]mock static methods in ecmascript

我有一個在另一個類中使用的靜態類。 要進行單元測試,我需要模擬該類,但如何模擬?

import {StaticClass} from '';

class UserClass {
  method() {
    StaticClass.staticMethod();
  }
}


it('should call staticMethod', () => {
  new UserClass().method();
  expect(StaticClass.staticMethod).toHaveBeenCalled();
})

您應該使用存根/模擬庫,例如sinonjs

例如

user.js

import { StaticClass } from './static';

export class UserClass {
  method() {
    StaticClass.staticMethod();
  }
}

static.js

export class StaticClass {
  static staticMethod() {
    console.log('staticMethod implementation');
  }
}

user.test.js :

import { UserClass } from './user';
import sinon from 'sinon';
import { StaticClass } from './static';

describe('64135983', () => {
  it('should pass', () => {
    const staticMethodStub = sinon.stub(StaticClass, 'staticMethod');
    new UserClass().method();
    sinon.assert.calledOnce(staticMethodStub);
    staticMethodStub.restore();
  });
});

單元測試結果:

  64135983
    ✓ should pass


  1 passing (10ms)

-----------|---------|----------|---------|---------|-------------------
File       | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
-----------|---------|----------|---------|---------|-------------------
All files  |      80 |      100 |      50 |      80 |                   
 static.ts |      50 |      100 |       0 |      50 | 3                 
 user.ts   |     100 |      100 |     100 |     100 |                   
-----------|---------|----------|---------|---------|-------------------

很容易,我可以使用 spyOn 方法來檢查我的方法是否已被調用。

spyOn(StaticClass, 'staticMethod').and.returnValue('mock value');

另外我需要使用 expect 來檢查它是否已被調用

expect(StaticClass.staticMethod).toHaveBeenCalled();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM