我正在尝试编写一个测试目标,如果使用jest
和vue-test-utils
正确地在HTML中传递默认道具。我似乎找不到我的目标选择器。我希望能够测试一个特定的p
标签包含正确的文本。在这种情况下,如果传递了名称prop,则会呈现该名称。如果不是,则默认函数呈现默认的payTo
值。
我一直在尝试几种链接到包装的组合无济于事。
console.log(wrapper.html()) // presents all the page html
console.log(wrapper.classes()) // array showing only one class ('.row-space-between')
这是我的组件:
<template>
<div class="row-space-between">
<div>
<h3>{{ $t('label.payTo') }}</h3>
<p>{{ merchantName.payTo }}</p> // TARGET SELECTOR
</div>
<div class="align-right">
<h3>{{ $t('label.estimatedTotal') }}</h3>
<p>{{ amount }}</p>
</div>
</div>
</template>
<script>
export default {
name: 'PayTo',
props: {
'merchant-name': {
type: Object,
// default: {} with type obj or arr default function is required
default: function () {
return { merchantName: {
payTo: 'Order Total'
}
}
},
amount: {
type: String,
default: ''
}
}
}
这是我的测试:
describe('PayTo.vue', () => {
let wrapper
beforeEach(() => {
wrapper = shallowMount(PayTo, {
mocks: {
$t
},
propsData: {
merchantName: {
payTo: 'foo-merchant-name'
},
amount: '$110.00'
}
})
})
it('[positive] should render correct contents', () => {
// PayTo.props.merchantName.default()
expect(wrapper.html()).toMatchSnapshot()
})
// The following two tests satisfy testing the default function in PayTo.vue props validation if not tested, coverage falls to zero
// This test is meaningless until I can be more specific in targeting
it('[positive] should display `AWS`', () => {
wrapper.setProps({
merchantName: {
payTo: 'AWS'
}
})
expect(wrapper.contains('p'))
})
it('[negative] should display `Order Total`', () => {
wrapper.setProps({
merchantName: {
payTo: 'Order Total'
}
})
console.log(wrapper.contains('div > p'))
expect(wrapper.contains('p'))
})
可以在这里使用:first-child
伪类:
expect(wrapper.contains("div:first-child > p")).toBeTruthy()
我还要验证p
中的文本是否符合预期值:
expect(wrapper.find("div:first-child > p").text()).toBe("Order Total")
另请注意,您的merchant-name
prop的默认值不应包含另一个merchantName
键。否则,当未指定该道具时,payTo
将访问merchantName.merchantName.payTo
。
props: {
"merchant-name": {
type: Object,
default: function() {
return {
// merchantName: { // DON'T DO THIS
// payTo: "Order Total"
// }
payTo: "Order Total"
}
}
},
}