Vue3 计算 属性 仅在 运行 测试时才重新评估(通过 karma/jasmine)

Vue3 computed property not re-evaluated only when running tests (via 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 对象。 See here.

所以我相信您只需进行一些小的调整就可以让它正常工作。

// 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
    });
});