对本机Webview onNavigationStateChange不起作用(运行笑话测试时)

时间:2019-05-07 11:13:07

标签: javascript react-native webview jestjs

我有一个来自react-native-community的import { WebView } from 'react-native-webview';。在我的本机应用程序中实现的是这样的:

<WebView
  key={ this.state.uri }
  source={{ uri: this.state.signedIn && this.state.shareUrl || this.state.uri }}
  style={{ width: '100%', height: '100%' }}
  onMessage={this.onMessage}
  onNavigationStateChange={this.setWebViewUrlChanged}
  onLoadEnd={syntheticEvent => {
    this.setState({ loading: false });
  }}
  onLoadStart={syntheticEvent => {
    this.setState({ loading: true });
  }}
/>

当我从正在运行的应用程序中通过Webview调用window.location.realod(url)调用onNavigationStateChange道具

我的处理函数如下:

setWebViewUrlChanged = webviewState => {
  if (webviewState.url !== this.state.initialUrl) {
    this.setState({ uri: webviewState.url });
  }
};

并已在手机和仿真器上经过测试,可以完美运行。我什至在控制台之前/之后都记录了状态,并确认状态已更新并且调用了该函数。

但是,我正在尝试通过开玩笑的​​单元测试进行测试。

it('should set webview uri', () => {
  console.log(snap.children[0].children[0].children[0].children[0].props);
  snap.children[0].children[0].children[0].children[0].props.onNavigationStateChange({ url: 'some-new-url' });
  expect(snap.state().uri).toEqual('some-new-url');
});

运行测试时出现错误:

  

TypeError:   snap.children [0] .children [0] .children [0] .children [0] .props.onNavigationStateChange   不是功能

并从上面的console.log行中获得了webviews道具,其中缺少此功能:

  { style:
     [ { flex: 1 },
       { backgroundColor: '#ffffff' },
       { width: '100%', height: '100%' } ],
    source:
     { uri: 'https://test-domain.eu.ngrok.io/static/dashboard/index.html' },
    injectedJavaScript: undefined,
    bounces: undefined,
    scrollEnabled: undefined,
    pagingEnabled: undefined,
    cacheEnabled: true,
    decelerationRate: undefined,
    contentInset: undefined,
    automaticallyAdjustContentInsets: undefined,
    hideKeyboardAccessoryView: undefined,
    allowsBackForwardNavigationGestures: undefined,
    incognito: undefined,
    userAgent: undefined,
    onLoadingStart: [Function],
    onLoadingFinish: [Function],
    onLoadingError: [Function],
    onLoadingProgress: [Function],
    onMessage: [Function],
    messagingEnabled: true,
    onShouldStartLoadWithRequest: [Function],
    scalesPageToFit: undefined,
    allowsInlineMediaPlayback: undefined,
    mediaPlaybackRequiresUserAction: undefined,
    dataDetectorTypes: undefined,
    useSharedProcessPool: true,
    allowsLinkPreview: undefined,
    showsHorizontalScrollIndicator: undefined,
    showsVerticalScrollIndicator: undefined,
    directionalLockEnabled: undefined }

因此,在测试的呈现的Webview中,仅onMessage函数与我的对象相同,但是我的所有onLoadStart / End和onNavigationStateChange均未呈现。

但是,当项目在设备上编译并运行时,这些缺少的功能可以很好地工作。我该如何解决这个问题,以便对这些功能进行单元测试?

在测试用例中使用的快照是这样生成的:

import renderer from 'react-test-renderer';

beforeEach(async () => {
  snapshot = renderer.create(<App />);
  snap = snapshot.toJSON();
});

1 个答案:

答案 0 :(得分:1)

我通过切换测试渲染器解决了它。我安装了enzymeenzyme-to-jsonenzyme-adapter-react-16

测试已修改:

describe('with setting', () => {
  let snapshot;

  beforeEach(async () => {
    // some mocking of asyncStorage
  });

  it('should match snapshot', async () => {
    snapshot = shallow(<App />)
    await new Promise((resolve) => setTimeout(resolve, 100)); // to allow async componentDidMount to finish.
    expect(snapshot).toMatchSnapshot()
  });

  it('should set webview uri', () => {
    snapshot.find('WebView').props().onNavigationStateChange({ url: 'some-new-url' });
    expect(snapshot.state().uri).toEqual('some-new-url');
  });
});

shallow功能来自在setup.js中配置笑话的酶

import Enzyme, { shallow, render, mount } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';

// React 16 Enzyme adapter
Enzyme.configure({ adapter: new Adapter() });

// Make Enzyme functions available in all test files without importing
global.shallow = shallow;
global.render = render;
global.mount = mount;

setst.js在简单的配置中指向(在我的情况下在package.json中)

"jest": {
    "preset": "react-native",
    "snapshotSerializers": [
      "enzyme-to-json/serializer"
    ],
    "setupFiles": [
      "<rootDir>/react-native/jest/setup.js"
    ]
  }

希望这将帮助那些在编译后的渲染组件和模拟的(测试)渲染组件之间未对齐的问题。