Jon*_*Tse 6 javascript unit-testing jestjs
export class Foo {
public static bar() {
doSomething();
}
constructor(paramA, paramB) {
}
}
Run Code Online (Sandbox Code Playgroud)
对于类中的方法,我们可以
jest.spyOn(Foo, 'bar')用来监视该方法。构造函数呢?我们如何监视对象的实例化?
小智 11
@gillyb 是对的,只是忘了“模拟” Foo 模块
// Foo.js
export class Foo {
public static bar() {
doSomething();
}
constructor(paramA, paramB) {
}
}
// Foo.spec.js
import Foo from './Foo.js';
jest.mock('./Foo.js');
it('test something...', () => {
// Assuming we did something that called our constructor
expect(Foo).toHaveBeenCalledTimes(1);
});
Run Code Online (Sandbox Code Playgroud)
如果你真的想监视构造函数,你可以这样做:
// MyClass.js
export class MyClass {
constructor() {
console.log("constructing");
}
}
// MyClass.test.js
import * as MyClassModule from './MyClass';
const MyClass = MyClassModule.MyClass;
test('the constructor is called', () => {
const constructorSpy = jest.spyOn(MyClassModule, 'MyClass');
new MyClass();
expect(constructorSpy).toHaveBeenCalledTimes(1);
});
Run Code Online (Sandbox Code Playgroud)
我认为没有官方的方法。这是我个人的做法:
const spy = jest.fn()
function Mock (...args) {
spy(...args)
Constructor.apply(this, args)
}
Mock.prototype = Constructor.prototype
Run Code Online (Sandbox Code Playgroud)
然后我可以检查间谍:
expect(spy).toHaveBeenCalledWith('firstArg', 'secondArg')
Run Code Online (Sandbox Code Playgroud)
gil*_*lyb -1
实际上有一种方法:)
甚至在官方文档中: https: //jestjs.io/docs/en/es6-class-mocks#complete-example
以下是您使用代码执行此操作的方法:
// Foo.js
export class Foo {
public static bar() {
doSomething();
}
constructor(paramA, paramB) {
}
}
// Foo.spec.js
import Foo from './Foo.js';
it('test something...', () => {
// Assuming we did something that called our constructor
expect(Foo).toHaveBeenCalledTimes(1);
});
Run Code Online (Sandbox Code Playgroud)