2016-10-28 7 views
0

jestを使用して模擬しようとしています。以下は試してみたい疑似コードです。 jestである。冗談を嘲笑いにいくつかの考えを投げてください。私はsinon.stub()に類似したものを探していて、resolve()を使って簡単に解決できます。ジョイントを使って非同期モックが動作しない、より良い方法や簡単な方法がありますか?

class ExampleService { 
    static get() { 
    agent.get("/examples") 
    } 
} 

ExampleStore:

class ExampleStore { 
    const examples = [] 
    getExamples() { 
    ExperimentService.get().then((result) = > { 
     this.examples = result 
    }) 
    } 
} 

のテストケース:

describe("ExampleStore",() = > { 
it("getExamples",() = > { 
    data = [{ 
    test: "test" 
    }] 
    ExperimentService.get = jest.fn(() = > { 
    return new Promise((resolve) = > { 
     process.nextTick(resolve(data) 
     }) ExampleStore.getExamples() expect(ExampleStore.examples).toBe(data) 
    } 
    }) 
}) 

答えて

0

あなたは独自の実装でExperimentService.getを模擬するためにjest.mockを使用することができます:私はありません

import ExampleStore from './ExampleStore' 
jest.mock('path/to/ExperimentService'() =>({ 
    get:()=> return Promise.resolve({test: 'test'}); 
    //get:()=> {then: (fn)=> fn({test: 'test'})} if you don't want to mess with promises in your test 
})) 

describe("ExampleStore",() => { 
it("getExamples",() => { 
    ExampleStore.getExamples() 
    expect(ExampleStore.examples).toBe(data) 
    } 
    }) 
}) 

シュルそれは通常、あなたが解決しようとすることを待つ必要があり、テストからの約束を返す必要があるので、私たちは非同期的に待機します。 how to handle promisesをご覧ください。 したがって、コメントアウトソリューションを使用してgetを偽装するか、 をExampleStore.getExampleに返すかのいずれかで、テストでそれを待つことができます。

関連する問題