Reputation: 1183
I am having trouble getting my Jasmine test file to get data from my knockoutjs files. I am able to create knockout observables and test those in the the spec file but not other files. For some reason when I try to access mainViewModel()
in the spec file from the viewmodel.js file it is not found. I have all the requirejs files included/defined but for some reason it is still not working.
Here is my code:
viewmodel.js:
define(["knockout", "jquery"], function (ko, $) {
var data = {
Name:"The Plan",
Id: 1
};
var TestViewModel = function (data) {
var self = this;
self.planName = ko.observable(data.Name);
self.planId = ko.observable(data.Id);
return self;
}
function mainViewModel() {
var self = this;
self.plan = ko.observableArray([]);
self.plan.push(new TestViewModel(data));
}
return mainViewModel;
});
someSpec.js file:
define(["knockout", "jquery"], function (ko, $) {
describe("MyTestSpec", function () {
var viewmodel, data;
beforeEach(function () {
require(["knockout", "jquery", "testsViewModel"], function(ko, $, tvm){
viewmodel = tvm.mainViewModel();
});
});
it("should be able to connect to View Model file", function () {
expect(viewmodel.Id).toBe(1);
});
});
});
index.html file:
<script type="text/javascript" src="Scripts/jasmine.js"></script>
<script type="text/javascript" src="Scripts/jasmine-html.js"></script>
<script type="text/javascript" src="Scripts/boot.js"></script>
<script type="text/javascript" src="Scripts/require.js"></script>
<script type="text/javascript">
require.config({
paths: {
"jquery": './Scripts/jquery-1.10.2.min',
"knockout": './Scripts/knockout.debug',
"testViewModel" :"./Scripts/viewmodel",
}
});
// list spec files here
require(["knockout","jquery","specs/someSpec", "testViewModel"], function () {
window.onload();
});
</script>
Upvotes: 0
Views: 836
Reputation: 16688
Here are couple of things that you need to fix:
The AMD require
function with a callback is asynchronous. This means that viewmodel
won't be set until after your tests have run. Instead of using require
, just include testViewModel
as a dependency in your test's define
call. Alternatively, you can use the synchronous API form: tvm = require('testViewModel')
.
viewmodel.js
is returning the mainViewModel
function as the module export. So that's what you'll get when referencing it elsewhere. So instead of viewmodel = tvm.mainViewModel()
, you'd use viewmodel = tvm()
.
Upvotes: 1