6 javascript reactjs jestjs enzyme
我正在尝试使用 Jest 和 Enzyme 测试 React 组件。目前我的测试非常简单,我只是想确保组件安装:
import React from 'react';
import Enzyme, { shallow } from 'enzyme';
import EnzymeAdapter from 'enzyme-adapter-react-16';
import App from './App';
Enzyme.configure({
adapter: new EnzymeAdapter()
});
describe('App Component', () => {
const app = shallow(<App />);
it('renders successfully', () => {
expect(app).toMatchSnapshot();
});
});
Run Code Online (Sandbox Code Playgroud)
运行它会出现以下错误:
App Component › encountered a declaration exception
TypeError: window.TimerSDK is not a constructor
Run Code Online (Sandbox Code Playgroud)
有问题的行是这段代码:
this.timerSDK = new window.TimerSDK({ accessToken: token });
Run Code Online (Sandbox Code Playgroud)
TimerSDK是通过脚本标签加载的第三方脚本index.html。它不像 es6 模块那样导入。
实际使用应用程序时,上面的代码在浏览器中运行良好,但在运行测试时出错。
如何解决这个问题?
默认的测试环境是提供Jest的类似浏览器的环境jsdom,它提供了一个模拟的window对象global。
您可以调用require第三方脚本来获取其导出并在测试开始时将其设置为global(或)(或者如果每个测试都需要,则在设置模块中执行此操作):windowsetupFilesAfterEnv
global.TimerSDK = require('path-to-script'); // <= set the module exports on global
import React from 'react';
import Enzyme, { shallow } from 'enzyme';
import EnzymeAdapter from 'enzyme-adapter-react-16';
import App from './App';
Enzyme.configure({
adapter: new EnzymeAdapter()
});
describe('App Component', () => {
const app = shallow(<App />);
it('renders successfully', () => {
expect(app).toMatchSnapshot();
});
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
18172 次 |
| 最近记录: |