@lizzie
To test code with jQuery promises in Mocha, you can use the chai
assertion library along with sinon
to mock the promises. Here's a step-by-step guide on how to do this:
- Install Mocha, Chai, Sinon, and jQuery in your project using npm:
1
|
npm install mocha chai sinon jquery
|
- Create a test file (e.g., test.js) and require the necessary modules:
1
2
3
4
|
const { expect } = require('chai');
const sinon = require('sinon');
const $ = require('jquery');
const yourModule = require('./yourModule'); // import the module you want to test
|
- Write your test cases using Mocha's describe and it functions:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
|
describe('YourModule', () => {
it('should return the correct value when the promise resolves', (done) => {
const response = 'success';
// Use sinon to mock the promise
const promise = sinon.stub($, 'ajax').returns($.Deferred().resolve(response).promise());
// Call your function that returns a promise
yourModule
.yourFunction()
.then((result) => {
expect(result).to.equal(response);
done();
});
// Restore the original method
promise.restore();
});
it('should handle errors when the promise rejects', (done) => {
const error = new Error('An error occurred');
// Use sinon to mock the promise rejection
const promise = sinon.stub($, 'ajax').returns($.Deferred().reject(error).promise());
// Call your function that returns a promise
yourModule
.yourFunction()
.catch((err) => {
expect(err).to.equal(error);
done();
});
// Restore the original method
promise.restore();
});
});
|
- Make sure you have a module (e.g., 'yourModule.js') that contains the code you want to test, including the function that returns a jQuery promise:
1
2
3
4
5
6
7
8
9
10
11
12
|
const $ = require('jquery');
function yourFunction() {
return $.ajax({
url: 'http://example.com/api',
method: 'GET'
});
}
module.exports = {
yourFunction
};
|
- Run your Mocha tests by running mocha in the terminal:
This setup allows you to test code that uses jQuery promises in Mocha by using Sinon to mock the promises and Chai to make assertions on the results.