0

I had previously been unit testing my Knockout app and components with Jasmine and Karma. As I don't need these tests to test any of the DOM, I am switcing to Mocha.

I am testing a Knockout component like this (very simplified):

MyComponent.js:

function MyComponent(params) {
  this.forename = params.forename;
  this.surname = params.surname;
}

exports.MyComponent = MyComponent

ko.components.register('my-component', {
  viewModel: MyComponent,
  template: {
    fromUrl: 'my-component.html'
  }
});

MyComponent.test.js:

var expect = require("expect.js");
var MyComponent = require("./src/components/my-component/my-component");

describe("Should do stuff", function () {
  it("should do stuff, function () {
    var myComponent = new MyComponent({});
    expect(myComponent.forename).to.be(undefined);
  });
});

When I run this (using gulp-mocha), I get an error saying that ko is not defined. Now I'm pretty sure that I need to require knockout in MyComponent.js but I'm not sure how. I've tried doing:

var ko = require("ko");
... require("knockout");
... require("knockout.js");
...require("path/to/knockout/knockout");

And I still get this error message. What am I doing wrong here?

Ben Thomas
  • 3,180
  • 2
  • 20
  • 38

1 Answers1

2

Do you want to test the workings of your components with or without knockout?

If you want to test the components and they can be tested without knockout I'd suggest moving the registration (which is the only part I can see now that depends on knockout) to another file and test only the component itself.

If you do in fact need knockout to be present you might also depend on the browser via Knockout (I don't know knockout, so I'm not sure about this). In that case you are probably better of running using karma. (You can use mocha instead of jasmine with karma if you want).

Alternatively you can mock the ko functions using sinon, but that might just make it more complicated...

Simon Groenewolt
  • 10,607
  • 1
  • 36
  • 64