2016-12-12 64 views
2

我試圖用笑話爲我的web組件項目編寫測試。我已經在es2015預設中使用了babel。加載js文件時遇到問題。我有以下一段代碼,其中document對象有currentScript對象。但在測試環境下,它是null。所以我想嘲笑它一樣。但jest.fn()是不是真的有幫助。我該如何處理這個問題?在笑話中嘲笑`文檔'

一段代碼,其中笑話失敗。

var currentScriptElement = document._currentScript || document.currentScript; 
var importDoc = currentScriptElement.ownerDocument; 

測試用例我寫了。 component.test.js

import * as Component from './sample-component.js'; 

describe('component test', function() { 
    it('check instance', function() { 
    console.log(Component); 
    expect(Component).toBeDefined(); 
    }); 
}); 

以下是笑話

Test suite failed to run 

    TypeError: Cannot read property 'ownerDocument' of null 

     at src/components/sample-component/sample-component.js:4:39 

更新拋出的錯誤: 按照由安德烈亞斯Köberle建議,我甚至加全局變量,並試圖嘲笑像下面

__DEV__.document.currentScript = document._currentScript = { 
    ownerDocument: '' 
}; 
__DEV__.window = { 
    document: __DEV__.document 
} 
__DEV__.document.registerElement = jest.fn(); 

import * as Component from './arc-sample-component.js'; 

describe('component test', function() { 
    it('check instance', function() { 
    console.log(Component); 
    expect(Component).toBeDefined(); 
    }); 
}); 

但是沒有運氣

更新:我甚至嘗試了上面的代碼沒有__dev__。還通過將文檔設置爲全局。

+1

您是否嘗試過使用'global.document'? –

+0

yes..i have try that .. no luck .. – thecodejack

+0

因此,我基本上使用jsdom,如 'const jsdom = require('jsdom'); const documentHTML ='<!doctype html>

'; global.document = jsdom.jsdom(documentHTML); ' 在此之後,我會根據我想要的任何文檔以及我的測試中可用的文檔。 –

回答

5

我已經解決了這個問題,使用setUpFiles屬性在開玩笑。這將在jsdom之後和每次測試之前執行,這對我來說是完美的。

集setupFiles開玩笑地配置,例如:

"setupFiles": ["<rootDir>/browserMock.js"] 


// browserMock.js 
Object.defineProperty(document, 'currentScript', { 
    value: document.createElement('script'), 
}); 

理想的情況是加載webcomponents.js到填充工具的jsdom。

2

我可以解決使用上的NodeJS global範圍模塊同樣的問題,設置文件與文件模擬,在我的情況,getElementsByClassName

// My simple mock file 
export default { 
    getElementsByClassName:() => { 
     return [{ 
      className: 'welcome' 
     }] 
    } 
}; 

// Your test file 
import document from './name.component.mock.js'; 
global.document = { 
    getElementsByClassName: document.getElementsByClassName 
}; 
+0

是的..這只是它的非常簡單的用例...在webcomponents.js我們有大量的API互連。嘲笑他們是一個任務的地獄...... – thecodejack

+0

但在你的情況下,你需要準確地模擬? –

0

如果你像我一樣正在尋找嘲笑文件未定義(例如,對於服務器端/客戶端測試),我可以用我的object.defineProperty測試套件內,而不必使用setupFiles

例子:

beforeAll(() => { 
    Object.defineProperty(global, 'document', {}); 
})