Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update unit tests #526

Merged
merged 5 commits into from Apr 14, 2020
Merged
Changes from 1 commit
Commits
File filter
Filter file types
Jump to
Jump to file
Failed to load files.

Always

Just for now

migrate legacy sinon unit tests to jest

  • Loading branch information
christophertino committed Apr 9, 2020
commit f5f5650323a2c7abfb4fba9349e62e7cd753f278
@@ -17,7 +17,7 @@ module.exports = {
'./test/setup.js'
],
roots: [
'<rootDir>/src/',
'<rootDir>/test/',
'<rootDir>/app/'
],
testURL: 'http://localhost',
@@ -13,22 +13,34 @@

// Set stubs for all chrome.* methods and properties
import chrome from 'sinon-chrome';

// Mock fetch calls
import { enableFetchMocks } from 'jest-fetch-mock';
// Set up Enzyme for React Snapshot testing
import Enzyme from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';

Enzyme.configure({ adapter: new Adapter() });
enableFetchMocks();

// Fake the translation function to only return the translation key
global.t = function(str) {
return str;
};

// Helper function to fake Fetch response
global.mockFetchResponse = function(responseCode, responseData) {
fetch.mockReturnValue(Promise.resolve(new Response(responseData, {
status: responseCode,
headers: {
'Content-type': 'application/json'
}
})));
};

// Create global stubs
global.chrome = chrome;
chrome.runtime.getManifest.returns({
version: '7.0.0',
version: '8.5.0',
debug: true
});

@@ -0,0 +1,42 @@
/**
* Dispatcher.js Unit Tests
*
* Ghostery Browser Extension
* http://www.ghostery.com/
*
* Copyright 2020 Ghostery, Inc. All rights reserved.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0
*/

import dispatcher from '../../src/classes/Dispatcher';
import conf from '../../src/classes/Conf';

describe('dispatcher tests', () => {
let spy = jest.spyOn(dispatcher, 'trigger');

afterEach(() => {
jest.clearAllMocks();
});

test('dispatcher is triggered once for conf value not in SYNC_ARRAY', () => {
conf.paused_blocking = true;
return expect(spy).toHaveBeenCalledTimes(1);
});

test('clearAllMocks() works and callCount is reset to 0', () => {
return expect(spy).toHaveBeenCalledTimes(0);
});

test('dispatcher is triggered twice for conf value in SYNC_ARRAY', () => {
conf.alert_expanded = true;
return expect(spy).toHaveBeenCalledTimes(2);
});

test('dispatcher is triggered with correct arguments', () => {
conf.alert_expanded = true;
return expect(spy).toHaveBeenCalledWith(`conf.save.alert_expanded`, true);
});
});
@@ -1,10 +1,10 @@
/**
* /src/classes/PolicySmartBlock.js Unit Tests
* PolicySmartBlock.js Unit Tests
*
* Ghostery Browser Extension
* http://www.ghostery.com/
*
* Copyright 2019 Ghostery, Inc. All rights reserved.
* Copyright 2020 Ghostery, Inc. All rights reserved.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
@@ -1,10 +1,10 @@
/**
* /src/classes/BugDb.js Unit Tests
* BugDb.js Unit Tests
*
* Ghostery Browser Extension
* http://www.ghostery.com/
*
* Copyright 2019 Ghostery, Inc. All rights reserved.
* Copyright 2020 Ghostery, Inc. All rights reserved.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
@@ -104,17 +104,8 @@ describe('src/classes/BugDb.js', () => {
};

beforeAll(done => {
// Fake the translation function for categories for bugDb.init()
global.t = sinon.stub();
global.t.withArgs([
'site_analytics',
'customer_interaction',
'social_media'
]).returns(true);

// Fake XMLHttpRequest for fetchJson(/databases/bugs.json)
sinon.stub(global, 'fetch');
setFetchStubResponse(200, JSON.stringify(bugs))
global.mockFetchResponse(200, JSON.stringify(bugs))

chrome.storage.local.get.yields({ previousVersion: "8.0.8" });
conf.init().then(() => {
@@ -125,21 +116,6 @@ describe('src/classes/BugDb.js', () => {
}).catch(err => console.log(err));
});

afterAll(() => {
global.fetch.restore();
});

// Helper function to fake XHR requests
function setFetchStubResponse (responseCode, responseData) {
const res = new global.Response(responseData, {
status: responseCode,
headers: {
'Content-type': 'application/json'
}
});
global.fetch.returns(Promise.resolve(res));
}

describe('bugDb.db.[key] should not be empty', () => {
test('bugs', () => expect(_.size(bugDb.db.bugs)).toBeGreaterThan(0));
test('apps', () => expect(_.size(bugDb.db.apps)).toBeGreaterThan(0));
@@ -303,7 +279,7 @@ describe('src/classes/BugDb.js', () => {
conf.bugs = old_bugs;

// Fake the xhr request again
setFetchStubResponse(200, JSON.stringify(bugs))
global.mockFetchResponse(200, JSON.stringify(bugs))

// fake an upgrade so that we read the "newer" bugs from disk instead of localStorage
return bugDb.init(true).then(() => {
@@ -1,10 +1,10 @@
/**
* /src/utils/common.js Unit Tests
* Common.js Unit Tests
*
* Ghostery Browser Extension
* http://www.ghostery.com/
*
* Copyright 2019 Ghostery, Inc. All rights reserved.
* Copyright 2020 Ghostery, Inc. All rights reserved.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
@@ -1,20 +1,18 @@
/**
* /src/classes/Conf.js Unit Tests
* Conf.js Unit Tests
*
* Ghostery Browser Extension
* http://www.ghostery.com/
*
* Copyright 2019 Ghostery, Inc. All rights reserved.
* Copyright 2020 Ghostery, Inc. All rights reserved.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0
*/

import chrome from 'sinon-chrome';
import conf from '../../src/classes/Conf';
import globals from '../../src/classes/Globals';
import dispatcher from '../../src/classes/Dispatcher';

describe('pre-initialization tests', () => {
test('pre-initialization global is set', () => {
@@ -33,7 +31,7 @@ describe('pre-initialization tests', () => {
return expect(conf.alert_bubble_timeout).toBeUndefined();
});

test('pre-initialization configuration values are saved temporarally', () => {
test('pre-initialization configuration values are saved temporarily', () => {
conf.alert_bubble_pos = 'tl';
return expect(globals.initProps.alert_bubble_pos).toBe('tl');
});
@@ -77,31 +75,3 @@ describe('post-initialization tests', () => {
return expect(chrome.storage.local.set.calledWith({alert_bubble_timeout: 30})).toBeTruthy();
});
});

describe('dispatcher tests', () => {
let spy = sinon.spy(dispatcher, 'trigger');

beforeEach(() => {
spy.resetHistory();
});

test('spy.resetHistory() works and callCount is reset to 0', () => {
return expect(spy.callCount).toBe(0);
});

test('dispatcher is triggered once for conf value not in SYNC_ARRAY', () => {
conf.paused_blocking = true;
return expect(spy.calledOnce).toBeTruthy();
});

test('dispatcher is triggered twice for conf value in SYNC_ARRAY', () => {
conf.alert_expanded = true;
return expect(spy.calledTwice).toBeTruthy();
});

test('dispatcher is triggered with correct arguments', () => {
conf.alert_expanded = true;
return expect(spy.calledWith(`conf.save.alert_expanded`, true)).toBeTruthy();
});

});
@@ -1,23 +1,23 @@
/**
* /src/classes/FoundBugs.js Unit Tests
* FoundBugs.js Unit Tests
*
* Ghostery Browser Extension
* http://www.ghostery.com/
*
* Copyright 2019 Ghostery, Inc. All rights reserved.
* Copyright 2020 Ghostery, Inc. All rights reserved.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0
*/

import _ from 'underscore';
import foundBugs from '../../src/classes/FoundBugs';
import bugDb from '../../src/classes/BugDb';
import conf from '../../src/classes/Conf';
import foundBugs from '../../src/classes/FoundBugs';

describe('src/classes/FoundBugs.js', () => {
const url = 'https://getsatisfaction.com/ghostery',
const url = 'https://feedback.ghostery.com/',
sources = [
// one app, three patterns, four sources
[2, "https://ssl.google-analytics.com/ga.js", true, 'SCRIPT'],
@@ -33,25 +33,13 @@ describe('src/classes/FoundBugs.js', () => {
];

beforeAll(done => {
// Fake the translation function for categories for bugDb.init()
global.t = sinon.stub();
global.t.withArgs([
'site_analytics',
'customer_interaction',
'social_media'
]).returns(true);

// Stub the fetch function
sinon.stub(global, 'fetch');

// Stub chrome storage methods so that our prefsGet() calls work.
chrome.storage.local.get.withArgs(['bugs']).yields({});
chrome.storage.local.get.withArgs(['compatibility']).yields({});
chrome.storage.local.get.withArgs(['tags']).yields({});
chrome.storage.local.get.yields({ previousVersion: "8.0.8" });

conf.init().then(() => {

//Start init sequence for testing. Changing the fakeServer() response each time for the following fetchJson() call
const bugsJson = JSON.stringify({
"apps": {"13": {"name": "Google Analytics","cat": "site_analytics","tags": [48]},
@@ -62,35 +50,19 @@ describe('src/classes/FoundBugs.js', () => {
"patterns": {'something': true},
"version":416
});
setFetchStubResponse(200, bugsJson);
// Mock bugDb fetch response
global.mockFetchResponse(200, bugsJson);
bugDb.init().then(() => {

// Fill foundBugs with fake data.
for (let i = 0; i < sources.length; i++) {
const source = sources[i];
foundBugs.update(url, source[0], source[1], source[2], source[3]);
}

done();
});
}).catch(err => console.log(err));
});

afterAll(() => {
global.fetch.restore();
});

// Helper function to fake XHR requests
function setFetchStubResponse (responseCode, responseData) {
const res = new global.Response(responseData, {
status: responseCode,
headers: {
'Content-type': 'application/json'
}
});
global.fetch.returns(Promise.resolve(res));
}

describe('testing source, pattern, and app counts', () => {
test('there should be seven sources', () => {
const bugSources = _.flatten(_.pluck(foundBugs.getBugs(url), 'sources'));
@@ -108,7 +80,6 @@ describe('src/classes/FoundBugs.js', () => {
test('getAppsCount() should get three apps', () => {
return expect(foundBugs.getAppsCount(url)).toBe(3);
});

});

describe('testing clear() functionality', () => {
@@ -1,10 +1,10 @@
/**
* /src/utils/matcher.js Unit Tests
* Matcher.js Unit Tests
*
* Ghostery Browser Extension
* http://www.ghostery.com/
*
* Copyright 2019 Ghostery, Inc. All rights reserved.
* Copyright 2020 Ghostery, Inc. All rights reserved.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
@@ -17,9 +17,6 @@ import { isBug } from '../../src/utils/matcher';

describe('src/utils/matcher.js', () => {
beforeAll(done => {
// Stub the fetch function
sinon.stub(global, 'fetch');

// Fake the XMLHttpRequest for fetchJson(/daabases/bugs.json)
const bugsJson = JSON.stringify({
"firstPartyExceptions": {
@@ -71,7 +68,8 @@ describe('src/utils/matcher.js', () => {
}
}
});
setFetchStubResponse(200, bugsJson);
// Mock bugDb fetch response
global.mockFetchResponse(200, bugsJson);

// Stub chrome storage methods so that our prefsGet() calls work.
chrome.storage.local.get.yields(null); //for Conf
@@ -86,21 +84,6 @@ describe('src/utils/matcher.js', () => {
}).catch(err => console.log(err));
});

afterAll(() => {
global.fetch.restore();
});

// Helper function to fake XHR requests
function setFetchStubResponse (responseCode, responseData) {
const res = new global.Response(responseData, {
status: responseCode,
headers: {
'Content-type': 'application/json'
}
});
global.fetch.returns(Promise.resolve(res));
}

describe('testing isBug()', () => {
describe('testing basic pattern matching', () => {
test('host+path tracker matching works', () => {
ProTip! Use n and p to navigate between commits in a pull request.