我有一个带有以下脚本的Vuejs应用程序(在Typescript中):
import { Foo, FooRepository } from "./foo";
import Vue from 'vue';
import Component from 'vue-class-component';
import { Promise } from "bluebird";
@Component
export default class MyComponent extends Vue {
isLoading: boolean;
fooData: Foo;
data() {
return {
isLoading: true,
fooData: new Foo()
}
}
created() {
this.populate();
}
populate() {
console.log("populate");
new FooRepository().get().then((data: Foo) => {
console.log(data);
this.isLoading = false;
this.fooData = data;
});
}
因此,在populate
挂钩上调用created
方法,repository.get()
返回Promise
,实施正在执行fetch
为了测试这个,我试图使用:
import * as fetch from "fetch-mock"
import Vue from "vue";
import { mount } from 'vue-test-utils';
import MyComponent from "./component.vue";
describe("Foo", () => {
afterEach(() => {
fetch.restore();
});
it("retrieves data", (done) => {
var comp = mount(MyComponent);
const response = { Title: "Hello, world" };
fetch.get("/api/called/from/repo", response);
Vue.nextTick(() => {
expect(comp.html()).toContain("Hello, world");
done();
});
});
});
我遇到的问题是在运行此测试时我得到:
Expected undefined to contain 'Hello, world'.
at eval (webpack-internal:///137:16:37)
at Array.eval (webpack-internal:///104:1790:12)
at flushCallbacks (webpack-internal:///104:1711:14)
at <anonymous>
奇怪的是,如果我将populate()
的实现更改为直接返回promise的内容,那么这样可以正常工作。
答案 0 :(得分:0)
您可以在测试时覆盖组件并覆盖创建的函数。
在您的组件中,您需要在created
和populate
created() {
return this.populate();
}
populate() {
return new FooRepository().get().then((data: Foo) => {
this.isLoading = false;
this.fooData = data;
});
}
在你的测试中:
it("retrieves data", (done) => {
let createdResult;
const MyComponentTest = Object.assign({}, MyComponent, {
created() {
const res = MyComponent.created.call(this);
createdResult = res;
return res;
},
});
const comp = mount(MyComponentText);
const response = { Title: "Hello, world" };
fetch.get("/api/called/from/repo", response);
createdResult.then(() => {
Vue.nextTick(() => {
expect(comp.html()).toContain("Hello, world");
done();
});
});
});