[英]mock static methods in ecmascript
I have a static class which is used in another class.我有一个在另一个类中使用的静态类。 To make a unit test, I need to mock that class but HOW?
要进行单元测试,我需要模拟该类,但如何模拟?
import {StaticClass} from '';
class UserClass {
method() {
StaticClass.staticMethod();
}
}
it('should call staticMethod', () => {
new UserClass().method();
expect(StaticClass.staticMethod).toHaveBeenCalled();
})
You should use a stub/mock library such as sinonjs .您应该使用存根/模拟库,例如sinonjs 。
Eg例如
user.js
: user.js
:
import { StaticClass } from './static';
export class UserClass {
method() {
StaticClass.staticMethod();
}
}
static.js
: static.js
:
export class StaticClass {
static staticMethod() {
console.log('staticMethod implementation');
}
}
user.test.js
: 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();
});
});
unit test result:单元测试结果:
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 |
-----------|---------|----------|---------|---------|-------------------
Easily, I could use spyOn method to check whether my method has been called.很容易,我可以使用 spyOn 方法来检查我的方法是否已被调用。
spyOn(StaticClass, 'staticMethod').and.returnValue('mock value');
Also I need to use expect to check whether it has been called另外我需要使用 expect 来检查它是否已被调用
expect(StaticClass.staticMethod).toHaveBeenCalled();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.