如何解决如何为单元测试正确模拟数据对象?
class Myviewmodel : Androidviewmodel() {
/**
* Indicates whether or not an empty state message should be displayed.
*/
val noMatchingDataLiveData: LiveData<Boolean> by lazy {
noMatchingDataSubject
// Ignore the first value
.skip(1)
// Only emit after every 2 items,since each data change from the adapter emits 2 messages
.buffer(2)
// Only emit the most recent of the 2 items
.map { it.last() }
.toFlowable(BackpressureStrategy.LATEST)
// Transforms an RX observable to a LiveData via LiveDataReactiveStreamsKt
.toLiveData()
}
/**
* The backing subject for [noMatchingDataLiveData].
*/
private val noMatchingDataSubject = BehaviorSubject.createDefault<Boolean>(false)
/**
* The recycler view adapter.
*/
internal val myRecyclerAdapter: FirestoreRecyclerAdapter<MyWidget,MyWidgetViewHolder> by lazy {
object : FirestoreRecyclerAdapter<MyWidget,MyWidgetViewHolder>(...) {
override fun onCreateViewHolder(group: ViewGroup,i: Int): MyWidgetViewHolder {
return MyWidgetViewHolder(LayoutInflater.from(group.context).inflate(R.layout.my_widget_item,group,false))
}
override fun onBindViewHolder(
holder: MyWidgetViewHolder,position: Int,model: MyWidget) {
...
}
override fun onDataChanged() {
// Note that each time the query is changed,this is invoked twice:
// The first invocation always has 0 items,because the offline cache was just cleared
// The second invocation will have the number of items matching the query,when the offline cache is updated
// Our subject uses a buffer to only emit every-other item
noMatchingDataSubject.onNext(this.itemCount < 1)
}
override fun onError(e: FirebaseFirestoreException) {
...
}
}
}
}
在添加 .filter 用法后,我在现有测试中看到诸如“无法读取未定义的属性‘过滤器’”之类的错误。我怎样才能在我的单元测试中正确地模拟这个,以便过滤器被识别为一个函数?目前,测试正在传入一个如下所示的数据对象:
const getSubscriptions = {
options: {
async handler({query}) {
const workType = searchParams.get('workType');
return axios.get(url,{
headers: {
Authorization: `Bearer ${clientCredentials.access_token}`
}
}).then((response) => {
if (workType && workType.length > 0) {
if (workType === 'UnkNown') {
response.data._embedded = response.data._embedded.filter((subscriptions) => !subscriptions.systemProperties.workType);
} else {
response.data._embedded = response.data._embedded.filter((subscriptions) => subscriptions.systemProperties.workType && subscriptions.systemProperties.workType === workType);
}
}
return response.data;
})
}
},method: 'GET',path: '/subscriptions'};
我尝试编辑此数据对象以包含 _embedded,然后我收到一个错误,指出 .filter 不是函数。
我是为 JavaScript 编写单元测试的新手,所以我已经坚持了一段时间。任何帮助表示赞赏。我正在使用 Mocha 进行测试,但也可能会解释 Jasmine 或 Jest 解决方案。
这是测试套件的精简版:
data: [chance.object(),chance.object()]
解决方法
代码试图过滤 response.data._embedded
数组 — response.data
是一个对象。您应该将响应数据模拟为对象(具有 _embedded
属性)而不是数组。
{
data: [chance.object(),chance.object()]
}
应该
{
data: {
_embedded: [
// ...
]
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。