We're trying to figure out how to use Jest.js
with Knockout.js
. Essentially we want to create a small fragment of DOM such as:
<div class="card" data-bind="component: myCustomComponent"/>
Then be able to call ko.applyBindings()
with a custom view model, and that DOM fragment and for Knockout to load the component up against the view model, so we can then do a Jest snapshot test.
The bit we're struggling to work out, is how can I effectively create a DOM fragment that is suited to ko.applyBindings()
as it requires a DOM node which we're not sure how to create/select.
EDIT
I've played around with the answer from @user3297291 and put together the following example, which unfortunately I can't get to work. Here's my example that I've put together:
const jsdom = require("jsdom");
const ko = require("knockout");
describe("Knockout Test", () => {
beforeAll(() => {
ko.components.register("greeting", {
viewModel: function(params) {
//params.name = "test";
//this.message = ko.observable(`Hello ${params.name}`);
this.message = ko.observable("Hello World!");
},
template: '<span data-bind="text: message"/>'
});
});
it("test pass", (done) => {
jsdom.env(`<div class="wrapper"></div>`, [], (err, window) => {
var wrapper = window.document.querySelector(".wrapper");
var element = window.document.createElement("div");
element.setAttribute("data-bind", 'component: "greeting"');
wrapper.appendChild(element);
ko.applyBindings({ name: 'Ian' }, wrapper);
setTimeout(() => {
console.log(element.innerHTML);
expect(element.innerHTML).toMatchSnapshot();
done();
}, 10);
}
);
});
});
If I modify element.setAttribute("data-bind", 'component: "greeting"');
to be element.setAttribute("data-bind", 'text: name');
then it works correctly, but loading a component (which is what I actually want to do) always seems to result in an empty element.innerHTML
.
Here's a package.json if you want to reproduce, and I'm running npm run jest
:
{
"name": "kotest",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"jest": "jest"
},
"author": "",
"license": "ISC",
"dependencies": {
"jasmine": "^2.5.3",
"jest": "^18.1.0",
"jsdom": "^9.9.1",
"knockout": "^3.4.1"
}
}