In my Vuejs application, I have the following script written in 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;
});
}
The populate
method is executed on the created
hook. The repository.get()
function returns a Promise
, and internally it performs a fetch
.
To conduct tests, I am attempting to use the following setup:
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();
});
});
});
When running this test, I encounter the following error:
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>
An interesting observation is that changing the implementation of the populate()
method to directly return a promise resolves the issue.