test.js runs tests
- Mocha
- beforeEach(func) and afterEach(func) - Mocha functions that run code before and after each test in the block
- done() - Mocha function that indicates asynchronous test is finished executing (parameter from
it()
function)
- Chai
- assert.deepEqual(actual, expected) - Instead of testing if references refer to same array in memory (
actual === expected
), deep equality verifies the arrays contain elements with the same values
- SinonJS
- sinon.useFakeXMLHttpRequest() - Returns a mock or "fake" object for XHR called
FakeXMLHttpRequest
// Under the hood
const savedXhr = window.XMLHttpRequest;
window.XMLHttpRequest = FakeXMLHttpRequest;
- xhr.onCreate = function(xhr) - Subscribe to newly created
FakeXMLHttpRequest
objects
- xhr.restore() - Restore original functions
// Under the hood
window.XMLHttpRequest = savedXhr;
// test.js
describe("movieApi object", function() {
describe("getMovies() method", function() {
beforeEach(function() {
// Replace XMLHttpRequest with FakeXMLHttpRequest
this.xhr = sinon.useFakeXMLHttpRequest();
// For mocking responses to requests that movieApi will send
this.requests = [];
// Subscribe
this.xhr.onCreate = function(xhr) {
this.requests.push(xhr);
}.bind(this);
});
afterEach(function() {
// Restore original XMLHttpRequest
this.xhr.restore();
});
it("Makes XHR request with valid search string and returns an array of movies", function(done) {
const searchStr = "star";
// Expected JSON response when searching for "star"
const jsonStr = `
{
"Search": [
{
"Title": "Star Wars: Episode IV - A New Hope",
"Year": "1977",
"imdbID": "tt0076759",
"Type": "movie"
},
{
"Title": "Star Wars: Episode V - The Empire Strikes Back",
"Year": "1980",
"imdbID": "tt0080684",
"Type": "movie"
},
{
"Title": "Star Trek II: The Wrath of Khan",
"Year": "1982",
"imdbID": "tt0084726",
"Type": "movie"
}
]
}
`;
// Get array of movie objects created by JSON
const movieData = JSON.parse(jsonStr).Search;
movieApi.getMovies(searchStr, function(err, results) {
// Should be no error
assert.isNull(err);
// Deep equality means the arrays contain elements with the same values
assert.deepEqual(results, movieData);
done();
});
// Supply fake XHR response
this.requests[0].respond(200, { 'Content-Type': 'text/json' }, jsonStr);
});
it("Makes XHR request with invalid search string and returns an error", function(done) {
const searchStr = "sdfsdfdsfds";
const jsonStr = '{"Response":"False","Error":"Movie not found!"}';
movieApi.getMovies(searchStr, function(err, results) {
assert.equal(err, "Movie not found!");
done();
});
// Supply fake XHR response
this.requests[0].respond(200, { 'Content-Type': 'text/json' }, jsonStr);
});
});
});