<template>
<div class="Calculator">
<table cellspacing="10">
<tr>
<td colspan="4">
<input type="text" v-model="result" disabled>
</td>
</tr>
<tr>
<td class="button" @click="addNumber(7)">7</td>
<td class="button" @click="addNumber(8)">8</td>
<td class="button" @click="addNumber(9)">9</td>
<td class="operator" @click="setOperator('*')">x</td>
</tr>
<tr>
<td class="button" @click="addNumber(4)">4</td>
<td class="button" @click="addNumber(5)">5</td>
<td class="button" @click="addNumber(6)">6</td>
<td class="operator" @click="setOperator('-')">-</td>
</tr>
<tr>
<td class="button" @click="addNumber(1)">1</td>
<td class="button" @click="addNumber(2)">2</td>
<td class="button" @click="addNumber(3)">3</td>
<td class="operator" @click="setOperator('+')">+</td>
</tr>
<tr>
<td class="button" @click="addNumber(0)" colspan='2'>0</td>
<td class="button" @click="clear">C</td>
<td class="operator" @click="equal">=</td>
</tr>
</table>
</div>
</template>
<script>
export default {
data: function() {
return {
result: 0,
tmp_value: 0,
reset: false,
operator: undefined
}
},
methods: {
clear() {
this.result = 0;
this.tmp_value = 0;
this.operator = undefined;
return result;
},
addNumber(number) {
if(this.result == 0 || this.reset === true) {
this.result = '';
this.reset = false;
}
this.result += number.toString();
},
setOperator(operator) {
if(this.tmp_value != 0)
this.calculate();
this.tmp_value = this.result;
this.operator = operator;
this.reset = true;
},
equal() {
this.calculate();
this.tmp_value = 0;
this.operator = undefined;
},
calculate() {
let value = 0;
let firstNum = parseFloat(this.tmp_value);
let secondNum = parseFloat(this.result);
switch(this.operator) {
case '+':
value = firstNum + secondNum;
break;
case '-':
value = firstNum - secondNum;
break;
case '*':
value = firstNum * secondNum;
break;
case '/':
value = firstNum / secondNum;
}
this.result = value.toString();
}
}
}
</script>
<style>
.Calculator {
display: flex;
margin: 0 auto;
height: 100vh;
width: 200px;
font-size: 25px;
}
table {
width: 370px;
}
input {
display: block;
text-align: right;
height: 30px;
}
.operator {
background-color: orange;
border: 1px solid gray;
}
.button {
background-color:whitesmoke;
border: 1px solid gray;
}
</style>
因此,我尝试对称为“清除”的方法之一进行单元测试,该方法基本上将屏幕结果更改为0,而我想测试实际上将其切换为0。 这是我的单元测试,但它告诉我结果未定义。
import { expect } from 'chai'
import { shallowMount } from '@vue/test-utils'
import Calculator from '@/components/Calculator.vue'
describe('Calcualtor.vue', () => {
const msg = 'new message'
it('Test Method Add', () => {
const wrapper = shallowMount(Calculator)
expect(wrapper.vm.clear()).to.equal(0)
})
})
我希望测试通过的预期结果,因为这些方法会将结果切换回0。
答案 0 :(得分:0)
好像您刚刚遇到一个小错字:
在clear
中,您返回的是result
(即undefined
),而不是this.result
:
clear() {
this.result = 0;
this.tmp_value = 0;
this.operator = undefined;
return this.result; // <= return "this.result" instead of "result"
},