我們先回顧一下這是昨天的樣子,還滿醜的吧?
css 的部分我們一概還沒做,這個並不急
但其中有一個很不優的地方我們要調整
就是圖片的位置
<template>
<div>
<div v-for="post in posts" class="post">
<h1>{{ post.title }}</h1>
<span>{{ post.author }}</span>
<img v-if="post.thumbnail" :src="post.thumbnail" alt="" class="thumbnail">
// 這邊我們 hard code 圖片的位置
// 但這樣實際上是載不到圖片的
<img v-else src="placeholder.jpg" alt="" class="thumbnail">
<button @click="showContent = !showContent" class="show-btn"></button>
<p v-if="showContent" class="content"></p>
</div>
</div>
</template>
<script>
export default {
name: 'board',
data () {
return {
posts: []
}
}
}
</script>
<style scoped>
</style>
這樣要拉到實際的圖片要怎麼做?
<script>
import placeHolder from '@/assets/placeholder.png'
export default {
name: 'board',
data () {
return {
placeHolder,
posts: []
}
}
}
</script>
然後對應到測試
beforeEach(() => {
wrapper = mount(Board, {
data: { posts, placeHolder: "placeholder.jpg" }
})
})
it('should have a placeholder if post has no thumbnail', () => {
picture('placeholder.jpg', '.post:nth-child(2) .thumbnail')
})
這樣的確就解決了,不過 vue-cli 這邊沒寫好
再跑 npm run watch 的時候會崩潰
FAIL test/unit/specs/Board.spec.js
● Test suite failed to run
/Users/mos/Documents/work/tutorial/project/reddit/src/assets/placeholder.png:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){�PNG
^
SyntaxError: Invalid or unexpected token
at ScriptTransformer._transformAndBuildScript (node_modules/jest-runtime/build/script_transformer.js:305:17)
at src/components/Board.vue:8:20
at Object.<anonymous> (src/components/Board.vue:36:3)
Test Suites: 1 failed, 1 total
Tests: 0 total
Snapshots: 0 total
Time: 2.005s
Ran all test suites related to changed files.
這個問題主要是,缺少一個 transform 的規則給 jest
我的做法是,補上一個 assets.transform.js 的檔案在 /test/unit/
const path = require('path')
module.exports = {
process (src, filename, config, options) {
return 'module.exports = ' + JSON.stringify(path.basename(filename)) + ';'
}
}
然後,在 /test/unit/jest.conf.js 裡面
補上 transform 的規則
transform: {
'\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$':
'<rootDir>/test/unit/assets.transform.js',
'^.+\\.js$': '<rootDir>/node_modules/babel-jest',
'.*\\.(vue)$': '<rootDir>/node_modules/vue-jest'
},
趕在 12點前問題解決!