3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【Karma + Jasmine】通信を含む場合のテストコード

Posted at

通信を含むメソッドのテストを書く.

# sample.coffee

class Sample
    getData: ->
        url = "http://example.com/1/json"
        
        xhr = new XMLHttpRequest()
        xhr.open("GET", url, false)
        xhr.send()
        
        data = null
        
        if xhr.status is 200
            data = JSON.parse(xhr.responseText)
            
        return data

.getData のテストを書く際に,xhrの通信部分をスタブしたい.

jasmine-ajaxjasmine-jquery を使用する.

$ npm install jasmine-ajax --save-dev
$ npm install jasmine-jquery --save-dev
sampleSpec.coffee
describe Sample, ->
    beforeAll ->
        jasmine.Ajax.install()
    afterAll ->
        jasmine.Ajax.uninstall()
    
    describe '.getData', ->
        beforeEach ->
            mockedData = {sample: 1}
    
            requestUrl = "http://example.com/1/json"
            jasmine.Ajax.stubRequest(requestUrl).andReturn
                status: 200
                responseText: JSON.stringify(mockedData)
                
            @sample = new Sample()
            
        it 'should got data', ->
            expect(@sample.getData().toBe({sample: 1})

beforeAllで jasmine.Ajax.install() する.
.getData() 呼び出し時のxhrリクエストをスタブし,返り値のテストをしている.

3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?