Vue3计算属性只有在运行测试时才不重新计算(通过karma/jasmine)



我正试图为带有karma/jasmine的Vue 3组件的计算属性编写一个断言值的测试。当应用程序运行时,计算属性会改变,并不断被重新评估,但在测试中似乎不会被重新评估。下面是一个非常简单的代码,用于测试组件和测试本身:

// Component to test
const Component1 = defineComponent({
setup() {
const someString = inject("someString");
return { someString };
},
computed: {
isSuccess(): boolean {
return this.someString == "success";
}
}
});
export default Component1;
// Test
import "Component1" from "/path/to/component";
describe("Component1 tests", function() {
let wrapper: VueWrapper<any>;
let inTest: any;
beforeEach(function(){
wrapper = mount(Component1, {
global: {
provide: {
someString: 'failure'
}
}
});
inTest = wrapper.vm;
});
describe("isSuccess should return true if someString is 'success'", function(){
expect(inTest.isSuccess).toBeFalse(); // this passes
inTest.someString = 'success';
expect(inTest.isSuccess).toBeTrue(); // but this fails
});
});

我错过了什么吗?

提供价值不是被动的,除非你通过ref财产或reactive对象。看到这里。

所以我相信你只需要做一些小小的调整就可以让它工作。

// Test
import { ref } from 'vue'
import "Component1" from "/path/to/component";
describe("Component1 tests", function() {
let wrapper: VueWrapper<any>;
let providedValue = ref('failure')
let inTest: any;
beforeEach(function(){
wrapper = mount(Component1, {
global: {
provide: {
someString: providedValue
}
}
});
inTest = wrapper.vm;
});
describe("isSuccess should return true if someString is 'success'", function(){
expect(inTest.isSuccess).toBeFalse(); // this passes
providedValue.value = 'success';
expect(inTest.isSuccess).toBeTrue(); // but this fails
});
});