2017-07-25 15 views
2

は、:冗談createSpyObj

chai.spy.object([ 'push', 'pop' ]); 

をジャスミンを使用すると、使用することができます。

jasmine.createSpyObj('tape', ['play', 'pause', 'stop', 'rewind']); 

冗談のものは何ですか?

コンテキスト:現在、(typescript)ジャスミンテストを(typescript)Jestに移行しています。移行ガイドは基本的にはこの場合役に立たない:https://facebook.github.io/jest/docs/migration-guide.html比較的新しい技術と同様に、これについてのドキュメントで簡単に見つけることのできるものは何もない。

答えて

2

私はしましたw ritten jestのための非常に速いcreateSpyObj関数。古いプロジェクトをサポートします。基本的にジャスミンの実装から移植されました。

export const createSpyObj = (baseName, methodNames): { [key: string]: Mock<any> } => { 
    let obj: any = {}; 

    for (let i = 0; i < methodNames.length; i++) { 
     obj[methodNames[i]] = jest.fn(); 
    } 

    return obj; 
}; 
1
const video = { 
    play() { 
    return true; 
    }, 
}; 

module.exports = video; 

とテスト:ここで見つける

const video = require('./video'); 

test('plays video',() => { 
    const spy = jest.spyOn(video, 'play'); 
    const isPlaying = video.play(); 

    expect(spy).toHaveBeenCalled(); 
    expect(isPlaying).toBe(true); 

    spy.mockReset(); 
    spy.mockRestore(); 
}); 

ドキュメント:https://facebook.github.io/jest/docs/en/jest-object.html#jestspyonobject-methodname

もありjest.fnされる()

const mockFn = jest.fn(); 
    mockFn(); 
    expect(mockFn).toHaveBeenCalled(); 

    // With a mock implementation: 
    const returnsTrue = jest.fn(() => true); 
    console.log(returnsTrue()); // true; 

https://facebook.github.io/jest/docs/en/jest-object.html#jestfnimplementation

+0

母は、私が知っていますスパイを作成する方法:Pあなたの例は、スパイを添付する方法を示しています。ですから、私がやったことをするためには、4行を追加する必要があります。 1つではなく、コンテキストが古いプロジェクトから切り替えているので、500個のテストを書き直すのは良い考えではありません。 – David

0

Davidの回答は正しいトラックで私を得るのを助けました。私はIonic3/Angular4プロジェクトでionic-mocks(https://github.com/stonelasley/ionic-mocks)を使用するように修正しました。

export function createSpyObj (baseName: string, methodNames: string[]): { [key: string]: jasmine.Spy } { 
    const obj: any = {} 
    for (let i: number = 0; i < methodNames.length; i++) { 
    obj[methodNames[i]] = jasmine.createSpy(baseName,() => {}) 
    } 
    return obj 
} 

は、その後、私は私のテスト/ specファイルでそのようにそれを使用することができるよ:私のテスト「ヘルパー」クラスで

は、私はこれを持っています。 (createSpyObjを使用している)

{ provide: AlertController, useFactory:() => AlertControllerMock.instance() }, 

とイオン-モックは冗談と互換性があるまで、私は私が欲しいモックをコピーする必要があります:私は、問題のプロバイダを注入

class AlertMock { 
    public static instance(): any { 
    const instance: any = createSpyObj('Alert', ['present', 'dismiss']) 
    instance.present.and.returnValue(Promise.resolve()) 
    instance.dismiss.and.returnValue(Promise.resolve()) 

    return instance 
    } 
} 

class AlertControllerMock { 
    public static instance (alertMock?: AlertMock): any { 

    const instance: any = createSpyObj('AlertController', ['create']) 
    instance.create.and.returnValue(alertMock || AlertMock.instance()) 

    return instance 
    } 
} 
関連する問題