test('2加2等于4', () => { expect(2+2).toBe(4); }); // 测试对象相等 test('测试对象的值', () => { const data = {a: 1}; expect(data).toEqual({a: 1}); }); // 测试不等,相反的值 test('2加2不等于1', () => { expect(2 + 2).not.toBe(1); }); |
test('null', () => { const n = null; expect(n).toBeNull(); expect(n).toBeDefined(); expect(n).not.toBeUndefined(); expect(n).not.toBeTruthy(); expect(n).toBeFalsy(); }); |
test('2加2', () => { const value = 2 + 2; expect(value).toBeGreaterThan(3); // 大于3 expect(value).toBeGreaterThanOrEqual(4); // 大于或等于4 expect(value).toBeLessThan(5); // 小于5 expect(value).toBeLessThanOrEqual(4.5); // 小于或等于4.5 }); |
test('两个浮点数字相加', () => { const value = 0.1 + 0.2; //expect(value).toBe(0.3); 这句会报错,因为浮点数有舍入误差 expect(value).toBeCloseTo(0.3); // 这句可以运行 }); |
test('there is no I in team', () => { expect('team').not.toMatch(/I/); }); test('but there is a "stop" in Christoph', () => { expect('Christoph').toMatch(/stop/); }); |
const shoppingList = [ 'diapers', 'kleenex', 'beer', ]; test('the shopping list has beer on it', () => { expect(shoppingList).toContain('beer'); }); |
function compileAndroidCode() { throw new Error('这是一个错误消息'); } test('compiling android goes as expected', () => { expect(compileAndroidCode).toThrow(); // 可以匹配异常消息的内容,也可以用正则来匹配内容 expect(compileAndroidCode).toThrow('这是一个错误消息'); expect(compileAndroidCode).toThrow(/消息/); }); |
npm i jest @types/jest |
it('Test async code with done', (done) => { setTimeout(() => { // expect something done(); }, 500) }); |
test("Test async code with promise", () => { // 一个rejected状态的 Promise 不会让测试失败 expect.assertions(1); return doAsync().then((data) => { expect(data).toBe('example'); }); }); test("Test promise with an error", () => { // 一个fulfilled状态的 Promise 不会让测试失败 expect.assertions(1); return doAsync().catch(e => { expect(e).toMatch('error') }); }); |
test("doAsync calls both callbacks", () => { expect.assertions(2); function callback1(data) { expect(data).toBeTruthy(); } function callback2(data) { expect(data).toBeTruthy(); } doAsync(callback1, callback2); }); |
// 假设 doAsync() 返回一个promise,resolve的结果为字符串'example' it('Test async code with promise', () => { expect.assertions(1); return expect(doAsync()).resolves.toBe('example'); }); }); it('Test promise with an error', () => { expect.assertions(1); return expect(doAsync()).rejects.toMatch('error')); }); |
// 假设 doAsync() 返回一个promise,resolve的结果为字符串'example' it('Test async code with promise', async () => { expect.assertions(1); const data = await doAsync(); expect(data).toBe('example'); }); }); |
// 假设 doAsync() 返回一个promise,resolve的结果为字符串'example' it('Test async code with promise', async () => { expect.assertions(1); await expect(doAsync()).resolves.toBe('example'); }); }); |
欢迎光临 51Testing软件测试论坛 (http://bbs.51testing.com/) | Powered by Discuz! X3.2 |