Here's the api for client.execute. I'm able to get a value back, but how am I able to actually test that the value is correct? I don't see a generic assert method anywhere.
http://nightwatchjs.org/api/execute.html
Nightwatch.js extends Node.js assert module, so you can also use any of the available methods there in your tests.
'some suite': function (client) {
client.execute(
function(greet){
return greet + " there!";
},
"Hello",
function(result){
client.assert.equal(result, "Hello there!");
}
);
}
Try with the following code:
'some suite': function(client) {
client.execute(function(args) {
return args + ' there!';
}, ['Hello'], function(result) {
client.assert.equal(result.value, "Hello there!");
});
},
You can write generic asserts with client.assert.equal. See more in the unit testing section http://nightwatchjs.org/guide#writing-unit-tests
Related
I have a constructor of a js object that looks like this:
function SomeThing(window, document) {
var self = this;
self.window = window;
self.document = document;
if (!self.window.sessionStorage.getItem('page-reloaded')) {
self.window.sessionStorage.setItem('page-reloaded', true);
self.window.location.reload(true); // PROBLEM ON THIS LINE
return;
}
}
my mock test looks like this:
beforeEach(function() {
mockWindowObj = {
'location': {
'href': '',
'search': '?hello=world',
'pathname': '/some/path',
'replace': function () {},
'reload': jasmine.createSpy()
}
};
spyOn(mockWindowObj.location, 'reload').and.callFake(function(){}); ;
some = new SomeThing(mockWindowObj, mockDocumentObj);
});
When I run a test I get this error:
PhantomJS 2.1.1 (Mac OS X 0.0.0) ERROR
{
"message": "Some of your tests did a full page reload!",
"str": "Some of your tests did a full page reload!"
}
If I comment out the line window.location.reload(true) all of my test run fine and pass. I'm sort of new to unit tests and I'm not sure how to get around this. Any help would be very much appreciated. Thanks in advance.
Your posted code cannot be what you actually ran. The line containing self.window.sessionStorage.getItem would have to fail since you did not define sessionStorage on your mock.
I guess the SomeThing function is being called with window pointing to the real window object. That explains what you observe.
I just started learning Jasmine test cases for angularjs. I am unable to test below code.Kindly help
$scope.getConstants = function(lovName) {
ConstantService.getConstants(lovName).then(function(d) {
switch (lovName) {
case 'WORKFLOW':
$scope.workflowTypes = d;
$scope.loadCounterpartyTmp();
break;
--------Other Cases
}
My ConstantService is defined as
App.factory('ConstantService', [ '$http', '$q', function($http, $q) {
return {
getConstants : function(lovName) {
return $http.post('/sdwt/data/getConstants/', lovName).then(function(response) {
return response.data;
}, function(errResponse) {
return $q.reject(errResponse);
});
}
I want to test getConstants function.I need to create a mock of ConstantService and pass the data to it.
I have written below test case but the test case is not working.Please let me know how to test the above code
describe('getConstantsForMurexEntity', function() {
it('testing getConstantsForMurexEntity function', function() {
var d=[];
d.push(
{id:1,value:'ABC'},
{id:2,value:'DEF'},
{id:3,value:'IJK'},
{id:4,value:'XYZ'},
);
//defined controller
spyOn(ConstantService, 'getConstants').and.returnValue(d);
$scope.getConstants('WORKFLOW');
expect($scope.workflowTypes).toBe(d);
The above test case is not working as it is saying "ConstantService.getConstants(...).then is not a function".
Your ConstantService.getConstants() function returns a promise, which your actual code is using, with the .then() call. This means means that when you spy on it, you also need to return a promise, which you are not doing. Because you are not returning a promise, when your actual call tries to call .then(), it is undefined, which is the reason for the error message.
Also, you aren't using Array.push correctly.
Your test should probably look something like the following (note, this is untested):
describe('getConstantsForMurexEntity', function() {
it('should set workflowTypes to the resolved value when lovName is "WORKFLOW"', inject(function($q) {
var deferred = $q.defer();
spyOn(ConstantService, 'getConstants').and.returnValue(deferred.promise);
var d = [
{id:1,value:'ABC'},
{id:2,value:'DEF'},
{id:3,value:'IJK'},
{id:4,value:'XYZ'},
];
$scope.getConstants('WORKFLOW');
deferred.resolve(d);
$scope.$apply();
expect($scope.workflowTypes).toBe(d);
}));
});
I have some RXJS code that does something like the following....
this.webSocketSubject = Observable.webSocket(url);
...
get webSocketStream() {
return this.webSocketSubject;
}
// Other Service
this.socketService.webSocketStream.filter(message => {
return message.method === "logout";
}).subscribe( this.onLogout );
Then in my test I try something like this...
socketService.sendMessage = jasmine.createSpy("Send Message Spy").and.callFake(function() {
socketService.webSocketStream.next(
{
method: "logout",
status: "OK"
}
)
});
// Just to confirm but doesn't get called
socketService.webSocketStream.subscribe(message => console.log("Ok it actually got called"))
But the subscribe code never gets called. I looked for other examples of test WS in RxJS but all I see is this and I can't get something similar working locally.
How do I test Observable.websocket in RxJS?
I had to resort to this but I don't like it.
constructor(private socket: Subject<any> = undefined ) {
if(!socket){
this.webSocketSubject = Observable.webSocket(url);
}
else{
this.webSocketSubject = socket;
}
};
In Jasmine 1.3, we had this option to the get current spec and suite names:
describe("name for describe", function () {
it("name for it", function () {
console.log(this.suite.getFullName()); // would print "name for describe"
console.log(this.description); // would print "name for it"
});
});
This does not longer work in Jasmine 2.x.
Anyone knows how to fetch those?
Thanks.
I add a new jasmine reporter, then get the spec name without define N variable on each spec. Hope can help, thanks.
var reporterCurrentSpec = {
specStarted: function(result) {
this.name = result.fullName;
}
};
jasmine.getEnv().addReporter(reporterCurrentSpec);
The reason this no longer works is because this is not the test. You can introduce a subtle change to your declarations however that fix it. Instead of just doing:
it("name for it", function() {});
Define the it as a variable:
var spec = it("name for it", function() {
console.log(spec.description); // prints "name for it"
});
This requires no plug-ins and works with standard Jasmine.
As far as Jasmine 2 is concerned currentSpec is discontinued on purpose. However there is a custom plugin/library developed that is based on jasmine reporter plugin which you can use. Here's the Link. Hope it helps with your requirement.
Its very simple to use, install the package with npm command -
npm install -g jasmine-test-container-support
Get the test container support by writing below lines before your describe or test suite -
var JasmineTestContainerSupport = window.JasmineTestContainerSupport || require('jasmine-test-container-support');
JasmineTestContainerSupport.extend(jasmine);
Later use the test container in your spec's to get its description -
var specDesc = jasmine.getEnv().getTestContainer();
Hope this helps.
var currentSpecName = describe('Test1', function() {
var currentStepName = it("Step1", function(){
console.log(currentStepName.description); // Prints It Name
console.log(currentSpecName.getFullName()); //Prints Describe Name
});
});
This worked for me in jasmine 3.5+
I know this is a relatively old question but found something which worked for me
describe('Desc1',() => {
afterEach(() => {
const myReporter = {
specDone: (result) => {
console.log('Spec FullName: ' + result.fullName);
console.log('Spec Result: ' + result.status);
}
};
jasmine.getEnv().addReporter(myReporter);
});
})
Credit for the solution : https://groups.google.com/g/jasmine-js/c/qqOk6Nh7m4c/m/Nyovy2EjAgAJ
This is probably a bit late but you can get the suite name outside the spec.
Please try the following code:
describe("name for describe", function () {
console.log(this.getFullName()); // would print "name for describe"
it("name for it", function () {
//Your test spec
});
});
The following test spec simulates calling a module that writes some content to the file system. Internally it uses fs to do that. I want to make sure fs.writeFile() was called with correct parameters. However, the toHaveBeenCalledWith() doesn't seem to work with a generic Function argument. Any ideas on how to make toHaveBeenCalledWith work as I expect?
Test Spec:
var fs = {
writeFile: function (arg1, arg2, cb){}
}
var writeContent = {
toFS: function (){
var path = "some/calculated/path";
var content = "some content";
fs.writeFile(path, content, function(){})
}
}
describe("writeContent", function() {
var writeFileSpy = null;
beforeEach(function() {
writeFileSpy = jasmine.createSpy('writeFileSpy');
spyOn(fs, 'writeFile').and.callFake(writeFileSpy);
});
it("can call spy with callback", function() {
writeContent.toFS();
expect(writeFileSpy).toHaveBeenCalledWith("some/calculated/path", "some content", Function);
});
});
Results:
Message:
Expected spy writeFileSpy to have been called with [ 'some/calculated/path', 'some content', Function ] but actual calls were [ 'some/calculated/path', 'some content', Function ].
Answering my own question :-) Just needed to enclose Function in jasmine.any() as in:
expect(writeFileSpy).toHaveBeenCalledWith("some/calculated/path", "some content", jasmine.any(Function));