我正在使用反应原生0.40和jest 20.当试图测试组件的内部方法时我失败了因为我无法得到它的实例然后调用该方法。
例如,我可以使用像
这样的快照测试渲染的组件# coding: utf-8
import urllib.request
from bs4 import BeautifulSoup
from selenium import webdriver
import pandas as pd
import time
from datetime import datetime
from collections import OrderedDict
import re
browser = webdriver.Firefox()
browser.get('https://www.kickstarter.com/discover?ref=nav')
categories = browser.find_elements_by_class_name('category-container')
category_links = []
for category_link in categories:
#Each item in the list is a tuple of the category's name and its link.category_links.append((str(category_link.find_element_by_class_name('f3').text),
category_link.find_element_by_class_name('bg-white').get_attribute('href')))
scraped_data = []
now = datetime.now()
counter = 1
for category in category_links:
browser.get(category[1])
browser.find_element_by_class_name('sentence-open').click()
time.sleep(2)
browser.find_element_by_id('category_filter').click()
time.sleep(2)
for i in range(27):
try:
time.sleep(2)
browser.find_element_by_id('category_'+str(i)).click()
time.sleep(2)
except:
pass
#while True:
# try:
# browser.find_element_by_class_name('load_more').click()
# except:
# break
projects = []
for project_link in browser.find_elements_by_class_name('clamp-3'):
projects.append(project_link.find_element_by_tag_name('a').get_attribute('href'))
for project in projects:
**page1 = urllib.request.urlopen(projects[counter])**
soup1 = BeautifulSoup(page1, "lxml")
**page2 = urllib.request.urlopen(projects[counter].split('?')**[0]+'/community')
soup2 = BeautifulSoup(page2, "lxml")
time.sleep(2)
print(str(counter)+': '+project+'\nStatus: Started.')
project_dict = OrderedDict()
project_dict['Category'] = category[0]
browser.get(project)
project_dict['Name'] = soup1.find(class_='type-24 type-28-sm type-38-md navy-700 medium mb3').text
project_dict['Home State'] = str(soup1.find(class_='nowrap navy-700 flex items-center medium type-12').text)
try:
project_dict['Backer State'] = str(soup2.find(class_='location-list-wrapper js-location-list-wrapper').text)
except:
pass
print('Status: Done.')
counter+=1
scraped_data.append(project_dict)
later = datetime.now()
diff = later - now
print('The scraping took '+str(round(diff.seconds/60.0,2))+' minutes, and scraped '+str(len(scraped_data))+' projects.')
df = pd.DataFrame(scraped_data)
df.to_csv('kickstarter-data.csv')
但是如果我尝试测试App组件的内部方法,我找不到任何方法来访问它。 因此以下代码将无法运行
it('renders correctly', () => {
var store = mockStore(initialState);
const tree = renderer.create(
<Provider store={store}>
<App/>
</Provider>
).toJSON()
expect(tree).toMatchSnapshot()
})
一些人使用的解决方案是“react-test-renderer / shallow”或“酶”浅层渲染组件并访问内部方法,但是当我导入它时可能找不到第一个(可能与RN版本有关) ?)和酶无法正确安装(可能再次,依赖性问题)。所以我想知道的是,测试内部方法的最佳方法是什么。
答案 0 :(得分:1)
您不必将组件实际包装在提供程序中。如果您只想测试组件,可以不使用connect()()
导出它。例如:
export class App extends React.Component {
// your things
}
export default connect()(App);
在测试文件中,您可以像这样导入您的应用:
import ConnectedApp, { App } from "../App";
然后,当您想测试封装的App
时,您可以像对待任何其他标准组件一样对待它:
const props = {
// mocked-out props your store would provide
};
const component = shallow(<App {...props} />);
component.instance().whateverMethodYouWant();
就个人而言,我从不在模拟提供程序中包装组件,除非我需要render
并且更深层的组件是connect
。