2016-12-12 68 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', {}); 
})